[백준/Java] 2230 수 고르기

HEETAE HEO·2022년 5월 21일
0


조건

  1. N개의 정수로 이루어진 수열을 받는다. ( 1 <= N <= 100,000 , int)

  2. 임의의 정수 2개의 차에 가까운 값을 찾는 기준 값 (0 <= M <= 2,000,000,000) , int

  3. 수열 내의 값의 범위는 (0 <= A[i] <= 1,000,000,000 , int)

  4. 임의의 정수 2개의 차를 구하는 거기 때문에 정수값이 정렬이 되어있지않는다면 음의 정수값이 나올 수 있으므로 수열을 정렬을 한다.

풀이(코드)

import java.io.*;
import java.util.*;



public class Main {
	
	static int N,M;
	static int A[];
	
	
	static FastReader scan = new FastReader();
	static StringBuilder sb = new StringBuilder();

	static void input() {
	
		N = scan.nextInt(); // 수열의 개수를 받음
		M = scan.nextInt(); // 임의의 정수 2개의 차 값의 기준이 될 값 
		A = new int[N + 1]; // 수열의 값을 받기위한 선언
		for(int i=1;i<=N;i++) {
			A[i] = scan.nextInt();
		}
	}



	static void find() {
    //값의 차가 음의정수가 발생하지않게 하기 위해 수열 정렬
		Arrays.sort(A,1,N+1);
	
		int R =1, ans = Integer.MAX_VALUE;
	//L의 위치를 고정하고 R의 위치를 하나씩 증가시키며 두 값의 차가 기준 값인 	// M보다 크거나 같으면서 근접한 값을 찾는다. 	
		for(int L = 1;L<=N;L++) {
			
			
			while(R+1 <= N && A[R] - A[L] < M) ++R;
			
			if(A[R] - A[L] >= M) ans = Math.min(ans, A[R] -A[L]);
		}
	
		System.out.println(ans);
	}
	

		
		
	public static void main(String[] args) {
		input();
		find();
	}
	
	static class FastReader{
		BufferedReader br;
		StringTokenizer st;
		
		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		
		public FastReader(String s) throws FileNotFoundException {
			br = new BufferedReader(new FileReader(new File(s)));
		}
		
		String next() {
			while(st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}
		
		int nextInt() {
			return Integer.parseInt(next());
		}
		Long nextLong() {
			return Long.parseLong(next());
		}
		double nextDouble(){
			return Double.parseDouble(next());
		}
		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			}catch(IOException e) {
				e.printStackTrace();
			}
			return str;
		}
	}
}
profile
Android 개발 잘하고 싶어요!!!

0개의 댓글