이번에 풀어본 문제는
백준 2470번 두 용액 입니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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());
int [] solutions = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
solutions[i] = Integer.parseInt(st.nextToken());
}
//정렬
Arrays.sort(solutions);
int answerLeft = 0, answerRight = 0;
int start = 0, end = N - 1;
int diff = Integer.MAX_VALUE;
while (start < end) {
int sum = solutions[start] + solutions[end];
int tmpDiff = Math.abs(sum);
// 기존보다 차이가 좁혀졌다면 값 저장
if (tmpDiff < diff) {
diff = tmpDiff;
// 오름차순 정렬되어있으므로, 무조건 left가 작은값
answerLeft = solutions[start];
answerRight = solutions[end];
}
// 양수면 값을 줄임
if (sum > 0) end--;
// 음수면 값을 늘림
else start++;
}
System.out.printf("%d %d", answerLeft, answerRight);
}
}
주어진 용액들을 섞은 결과가 0에 가장 가까운 쌍을 구하는 문제입니다.
배열을 정렬한 후, 양쪽 끝에서 시작하여 포인터를 이동시키며 값을 구해줍니다.
합이 양수일경우 값을 줄여야 0에 근접해지므로 end-- 음수는 반대로 늘려야 하므로 start++
정렬된 배열이므로 어차피 왼쪽 값이 무조건 작습니다. 따라서, left, right를 순서대로 출력해주면 해결할 수 있습니다.