알고리즘 풀이/백준

★ [백준][Java] 2470번 두 용액 (이진탐색)

배게 2021. 10. 18. 05:06
728x90

이진탐색으로 풀기 보다 그냥 인덱스 두 개 지정해줘서

좁혀주는 문제..?

절대값을 활용한다는 개념 때문에

갱신된 최소값의 용액의 합이 음일경우 i를 ++해주고

양일 경우에는 j를 --한다는 개념이..

이게 이진탐색이라기 보다는 다른 알고리즘의 문제 같음 태그보니까 두 포인터라는게 있었음..

 

참고 : https://maivve.tistory.com/129

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
 
 
 
public class Main {
        
    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
    
    public static void main(String[] args) throws IOException{
        int N = stoi(br.readLine());
        String[] str = br.readLine().split(" ");
        int[] solution = new int[N];
        for(int i=0; i<N; i++)
            solution[i] = stoi(str[i]);
        
        Arrays.sort(solution);
        
        int min = Integer.MAX_VALUE;
        int left = 0;
        int right = N-1;
        int a = -1, b = -1;
 
        while(left<right) {
            int sum = solution[left]+solution[right];
            int abs = Math.abs(sum);
            if(abs<min) {
                a = solution[left];
                b = solution[right];
                min = abs;
            }
            
            if(sum<0)
                left++;
            else
                right--;
        }
        
        System.out.println(a+" "+b);
        
        
        
        
//        bw.write("");
//        bw.flush();
//        bw.close();
    }
 
    private static int stoi(String input) {
        return Integer.parseInt(input);
    }
}
cs