99클럽 코테 스터디 20일차 TIL - 백준 N번째 큰 수

Gaeng·2024년 11월 16일
post-thumbnail

문제링크 - 백준 N번째큰수 2075\

해결방법 : 어제와 마찬가지 PriorityQueue를 통한 해결방법.

내가 푼 방법
문제를 풀면서 생각난 것, 어제 사용했던, PriorityQueue를 사용해 우선순위큐를 이용하면 힙이 최소값이 맨 앞에 있기때문에 역순으로 해서 구하고, 삭제를 할 때, N-1에서 출력하면 가능하다고 생각해서 풀었다.

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());	
        // 입력할 때, 큰수부터 나열하게 함.
        PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
        for(int i = 0; i<N; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int j = 0; j<N; j++){
                queue.add(Integer.parseInt(st.nextToken()));
            }              
        //반복문을 돌려서 0번째부터 돌아가기 때문에, N-1번째를 출력하면 정답이 나옴.
        for(int i = 0; i<N; i++){
            if(i==N-1){
                System.out.println(queue.poll());
            }else{
                queue.poll();
            }
        }
    }
}

다른 방법

  • 똑같이 입력을 받되 최소값을 받는 queue.size>N보다 크면 맨위의 최소값을 계속해서 지워가면, N일 때 맨위의 숫자가 그 수임.
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                int num = Integer.parseInt(st.nextToken());
                queue.add(num);
                if (queue.size() > N) {
                    queue.poll();
                }
            }
        }
        System.out.println(queue.peek());
    }
}
profile
문제를 해결하면서 나온 문제를 기록하는 노트

0개의 댓글