오늘은 여기까지
[백준] 1253 좋다 - 자바 Java 본문
https://www.acmicpc.net/problem/1253
- 투 포인터를 활용해 문제를 풀기 위해 숫자를 정렬해준다.
- 예를 들어, 현재 판별하려는 수가 5일때 `num[start]` 또는 `num[end]`가 5와 같은 경우 count를 증가 시키면 안된다.
- 이걸 생각 못해서(?) 한참 헤맸다.
import java.io.*;
import java.util.*;
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());
long[] num = new long[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
num[i] = Long.parseLong(st.nextToken());
}
Arrays.sort(num);
int target = 0, count = 0;
while (target < N) {
int start = 0, end = N - 1;
long sum = 0;
while (start < end) {
sum = num[start] + num[end];
if (sum == num[target]) {
if (start != target && end != target) {
count++;
break;
} else if (start == target) {
start++;
} else if (end == target) {
end--;
}
}
else if (sum < num[target]) {
start++;
} else if (sum > num[target]) {
end--;
}
}
target++;
}
System.out.println(count);
}
}
'Problem Solving' 카테고리의 다른 글
[프로그래머스] 택배상자 - 자바 Java (0) | 2024.07.25 |
---|---|
[프로그래머스] 두 개 뽑아서 더하기 - 자바 Java (1) | 2024.07.08 |
[프로그래머스] 프렌즈4블록 (Lv.2) - 자바 Java (0) | 2024.07.03 |
[프로그래머스] 귤 고르기 (해시 Lv.2) - 자바 Java (1) | 2024.07.01 |
[프로그래머스] 오픈채팅방 (Lv.2) - 자바 Java (1) | 2024.07.01 |