문제
https://www.acmicpc.net/problem/2230
풀이(8분)
import java.awt.Point;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = Integer.parseInt(br.readLine());
}
int answer = Integer.MAX_VALUE;
Arrays.sort(arr);
int start = 0;
int end = 1;
while(start < n && end < n){
int first = arr[start];
int second = arr[end];
int check = second - first;
if(check >= m){
if(answer > check){
answer = check;
}
start++;
}
if(check < m){
end++;
continue;
}
}
System.out.println(answer);
}
}
투포인터를 활용한 문제 해결이다. 먼저 배열을 오름차순으로 정렬해준 뒤 내가 원하는 값과 비교한다.
1. check >= m 인 경우
1-1. 정답보다 check가 작다면 정답을 갱신한다.
1-2. 이 후 start만 한 칸 미뤄준다. (여기서 start만 미뤄도 되는 이유는 어차피 start == end가 되면 check가 0이 되어 차후 처리된다.)
2. check < m인 경우
2-1. end만 한 칸 뒤로 미뤄준다.
'문제 풀이 > 백준' 카테고리의 다른 글
[백준] 24723번. 녹색 거탑(JAVA) (0) | 2024.11.29 |
---|---|
[백준] 15439번. 베라의 패션(JAVA) (0) | 2024.11.29 |
[백준] 1484번. 다이어트(JAVA) (0) | 2024.11.28 |
[백준] 14502번. 연구소(JAVA) (0) | 2024.11.28 |
[백준] 1074번. Z(JAVA) (1) | 2024.11.27 |