Untitled

 avatar
unknown
plain_text
16 days ago
558 B
2
Indexable
//Approach - (Using min-heap)
//T.C : O(n*logK)
//S.C : O(K)
class KthLargest {
    private PriorityQueue<Integer> pq;
    private int K;

    public KthLargest(int k, int[] nums) {
        K = k;
        pq = new PriorityQueue<>(K);

        for (int num : nums) {
            pq.offer(num);
            if (pq.size() > K) {
                pq.poll();
            }
        }
    }

    public int add(int val) {
        pq.offer(val);
        if (pq.size() > K) {
            pq.poll();
        }
        return pq.peek();
    }
}
Leave a Comment