congr / world

2 stars 1 forks source link

LeetCode : 703. Kth Largest Element in a Stream #406

Closed congr closed 5 years ago

congr commented 5 years ago

image

congr commented 5 years ago

K sized min heap

Keeping track of min heap which is size K.

congr commented 5 years ago
class KthLargest {
    PriorityQueue<Integer> minHeap;
    int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        minHeap = new PriorityQueue<Integer>(k);

        for(int n : nums) add(n); // !!! k sized min heap
        System.out.println(minHeap);
    }

    public int add(int val) {
        if (minHeap.size() < this.k) minHeap.add(val);

        else if (val > minHeap.peek()) {
            minHeap.remove();
            minHeap.add(val);
        }

        // System.out.println("return " + minHeap.peek());
        return minHeap.peek();
    }
}

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