문제풀이/백준
[백준]2470: 두 용액 - JAVA
빈둥벤둥
2021. 2. 10. 18:45
[백준]2470: 두 용액
2470번: 두 용액
첫째 줄에는 전체 용액의 수 N이 입력된다. N은 2 이상 100,000 이하이다. 둘째 줄에는 용액의 특성값을 나타내는 N개의 정수가 빈칸을 사이에 두고 주어진다. 이 수들은 모두 -1,000,000,000 이상 1,000,00
www.acmicpc.net
풀이
이분탐색 문제를 풀어보려고 풀었는데 풀고나니 이분탐색 문제보다는 투포인터? 라는 문제라고 한다.
배열을 정렬한 후 첫 인덱스와 마지막 인덱스 값을 증감하며 적절한 위치를 찾아주었다.
scanner를 써서 풀면 시간초과가 났다.
코드
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
|
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 NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] solution = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
solution[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(solution);
int s1 = 0, s2 = 0; //용액 정보를 저장
int s = 0;
int e = n - 1;
int min = Integer.MAX_VALUE;
while(s < e) {
int total = solution[s] + solution[e];
if(Math.abs(total) < min) {
min = Math.abs(total);
s1 = solution[s];
s2 = solution[e];
}
if(total < 0) { //total이 마이너스 값이라는 것은 s의 절댓값이 더 크다는 것을 의미. 0에 근사하게 만들기 위해 s의 인덱스를 증가시킨다.
s++;
} else e--;
}
System.out.println(s1 + " " + s2);
}
}
|
cs |