import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
if(n <= 2) {
System.out.println(0);
return;
}
int[] arr = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
int result = 0;
for(int i=0; i<n; i++) {
int start = 0; int end = n - 1;
while(true) {
if(start == i) start++;
else if(end == i) end--;
if(start >= end) break;
if(arr[start] + arr[end] == arr[i]) {
result++;
break;
} else if(arr[start] + arr[end] < arr[i]) {
start++;
} else {
end--;
}
}
}
System.out.println(result);
br.close();
}
}
❌ 틀린 답안 ❌
while(start < end) {} 로 하면 start++, end--로 인해 start가 end보다 같거나 커져도 도중에 break가 되지 않으므로 틀리게 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
if(n <= 2) {
System.out.println(0);
return;
}
int[] arr = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
int result = 0;
for(int i=0; i<n; i++) {
long target = arr[i];
int start = 0; int end = n - 1;
while(start < end) {
if(start == i) start++;
else if(end == i) end--;
if(arr[start] + arr[end] == target) {
result++;
break;
} else if(arr[start] + arr[end] < target) {
start++;
} else {
end--;
}
}
}
System.out.println(result);
br.close();
}
}
'Coding Test > 백준' 카테고리의 다른 글
[백준/자바] 11003 - 최솟값 찾기 (0) | 2023.06.04 |
---|---|
[백준/자바] 12891 - DNA 비밀번호 (0) | 2023.06.03 |
[백준/자바] 2018 - 수들의 합 5 (0) | 2023.06.03 |
[백준/자바] 10986 - 나머지 합 (0) | 2023.05.31 |
[백준/자바] 28061 - 레몬 따기 (0) | 2023.05.23 |