투 포인터 예제 - 3
Last updated
Last updated
n(데이터 개수)
result(좋은 수 개수 저장 변수)
a(수 데이터 저장 리스트)
a 정렬
for n번 반복:
변수 초기화(찾고하 하는 값 find = a[k], 포인터 i, 포인터 j)
while i < j:
if a[i] + a[j] == find:
두 포인터 i, j가 k가 아니면 좋은 수 개수 1 증가 및 while문 종료
두 포인터 i나 j가 k가 맞으면 포인터 변경 및 계속 수행
elif a[i] + a[j] < k:
포인터 i 증가
else:
포인터 j 감소
result 출력import sys
input = sys.stdin.readline
n = int(input())
result = 0
a = list(map(int, input().split()))
a.sort()
for k in range(n):
find = a[k]
i = 0
j = n - 1
while i < j:
if a[i] + a[j] == find:
if i != k and j != k:
result += 1
break
elif i == k:
i += 1
elif j == k:
j -= 1
elif a[i] + a[j] < find:
i += 1
else:
j -= 1
print(result)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());
int result = 0;
int[] a = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(a);
for (int k = 0; k < n; k++) {
int find = a[k];
int i = 0;
int j = n - 1;
while (i < j) {
if (a[i] + a[j] == find) {
if (i != k && j != k) {
result++;
break;
} else if (i == k) {
i++;
} else {
j--;
}
} else if (a[i] + a[j] < find) {
i++;
} else {
j--;
}
}
}
System.out.println(result);
}
}