[백준] 2473 세용액

` 이분 탐색

$O(N*NlogN)$의 시간복잡도여서 시간초과를 예상했으나 그렇진 않았다.

 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class B2473 {

	static int N;
	static long max = 3000000000L;
	static long[] arr , three = new long[3];
	public static void main(String[] args) throws  IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		arr = new long[N];
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		for (int i = 0; i < N; i++) {
			arr[i] = Long.parseLong(st.nextToken());
		}
		
		// 정렬해주기 
		Arrays.sort(arr);
		
		//n-2번의 이분 탐색
		for(int i=0;i<N-2;i++) {
			int left = i+1;
			int right = N-1;
			while(left < right) {
				long sum = arr[i] + arr[left] + arr[right];
				
				if(Math.abs(sum) < max) {
					three[0] = arr[i];
					three[1] = arr[left];
					three[2] = arr[right];
					max = Math.abs(sum);
				}
				
				if(sum>0) right--;
				else left++;
			}
			
		}
		
		System.out.println(three[0]+" "+three[1]+" "+three[2]);
		
	}

}
updatedupdated2021-04-052021-04-05
Load Comments?