Step-by-Step

[Java] Daily LeetCode Challenge 703. Kth Largest Element in a Stream 본문

언어/JAVA

[Java] Daily LeetCode Challenge 703. Kth Largest Element in a Stream

희주(KHJ) 2023. 5. 23. 21:38

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

 

Kth Largest Element in a Stream - LeetCode

Can you solve this real interview question? Kth Largest Element in a Stream - Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class:

leetcode.com

 

1차원적 접근과 PQ이용은 상당히 차이난다,,

 

PQ 이용해서 오름차순 정렬 후, 항상 size를 K로 유지하고 그때그때 Peek값 전달해주면 됨!

 

 

[코드]

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

    public KthLargest(int k, int[] nums) {
        this.k = k; 
        for(int i : nums)
            setHeap(i);
    }
    
    public int add(int val) {
        setHeap(val);
        return num.peek();
    }

    public void setHeap(int val){
        num.add(val);
        if(num.size() > k)
            num.poll();
    }
}

/*
 *
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 *
 */
Comments