반응형
[BOJ] 2467번 용액
https://www.acmicpc.net/problem/2467
문제 접근
용액의 값들이 정렬이 되어있어서 left와 right를 이용해서 이분 탐색 방식으로 접근했다.
절대값을 이용해서 절대값이 낮은 경우를 저장해놓고, sum이 0일 때 break하고, sum이 0보다 작을 때는 left 인덱스를 +1 해주고, sum이 0보다 크면 right 인덱스를 -1해서 0에 가까운 값을 찾았다.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ2467 {
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());
}
int left = 0;
int right = n-1;
int answer = Integer.MAX_VALUE;
int solution1=0, solution2=0;
while(left < right){
int sum = solutions[left] + solutions[right];
if(Math.abs(sum) < Math.abs(answer)){
answer = sum;
solution1 = solutions[left];
solution2 = solutions[right];
}
if(sum == 0){
break;
} else if(sum < 0){
left++;
} else {
right--;
}
}
System.out.println(solution1 + " " + solution2);
}
}
반응형
'Algorithm' 카테고리의 다른 글
[Algorithm/Java][백준] 2504번 괄호의 값 (0) | 2022.05.11 |
---|---|
[Algorithm/Java][백준] 1987번 알파벳 (0) | 2022.05.08 |
[Algorithm/Java][백준] 12852번 1로 만들기 2 (0) | 2022.05.01 |
[Algorithm/Java][프로그래머스] 단체사진 찍기 (0) | 2022.05.01 |
[Algortihm/Java][프로그래머스] 오픈채팅방 (0) | 2022.04.12 |