99클럽 코테 스터디 25일차 TIL - priority queue K번째 수

수삼·2024년 11월 22일
0

코딩테스트

목록 보기
31/44

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.*;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PriorityQueue<Integer> pq = new PriorityQueue();
        String[] arr = br.readLine().split(" ");

        StringTokenizer st = new StringTokenizer(br.readLine());
        while (st.hasMoreTokens()) {
            pq.offer(Integer.parseInt(st.nextToken()));
        }

        int cnt = Integer.parseInt(arr[1]);
        while (!pq.isEmpty() && cnt-- > 1) {
            pq.poll();
        }
        System.out.println(pq.peek());
    }
}

1. 숫자 정보를 받아 배열에 저장해놓는다.
2. 우선순위 큐에 두번째 줄 데이터를 넣는다.
3. 배열 두번째에 저장된 수를 가져와 바로 앞 숫자까지 꺼낸다. (3번째 숫자가 필요하면 2번째까지만 꺼낸다)
4. 가장 앞에 있는 수를 출력한다.

0개의 댓글