703. Kth Largest Element in a Stream

양성준·2025년 5월 12일

코딩테스트

목록 보기
49/102

문제

https://leetcode.com/problems/kth-largest-element-in-a-stream/description/

풀이

class KthLargest {
    int k;
    PriorityQueue<Integer> heap = new PriorityQueue<>();

    public KthLargest(int k, int[] nums) {
        this.k = k;
         for(int n : nums) {
            add(n);
        }
    }
    
    public int add(int val) {
        heap.add(val);
        if (heap.size() > k) {
            heap.poll();
        }
        return heap.peek();
    }
}
  • 지속해서 k번째로 높은 점수를 반환하는 클래스가 필요
    • min-heap를 만들고, k만큼의 크기를 유지시키면, 처음 뽑은 점수가 k번째로 큰 점수

k번째로 큰 수 -> k 크기의 min-heap에서 가장 처음 수

profile
백엔드 개발자

0개의 댓글