Home 14921번(용액 합치기)
Post
Cancel

14921번(용액 합치기)

해결

"용액 합치기"

코드

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
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));
        StringTokenizer st;

        int N = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        int[] input = new int[N];
        int result = Integer.MAX_VALUE;
        for(int i =0; i < N; i++) {
            input[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(input); // 이분탐색을 위한 정렬
        for(int i = 0; i < N; i++){
            int goal = -1 * input[i]; // 0을 만들기 위한 최적값
            int idx = Arrays.binarySearch(input,goal);
            if(idx < 0) {
                idx = ((idx + 1) * -1); // 값이 없으면 들어가야하는 자리값 계산
            }
            else {
                result = 0;
                break;
            }
            for(int j = 0; j <= 1; j++) {
                int nIdx = idx - j;
                if(nIdx >= N || nIdx < 0 || nIdx == i) continue;
                int num = input[nIdx] + input[i];
                if(Math.abs(result) > Math.abs(num)) result = num;
            }
        }
        System.out.println(result);
    }
}

참고

  • 직접구현
This post is licensed under CC BY 4.0 by the author.