Leetcode 703. 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 the KthLargest
class:
KthLargest(int k, int[] nums)
Initializes the object with the integer k and the stream of integers nums.
int add(int val)
Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
-10^4
to 10^4
.To efficiently solve this problem, we will use a minimum heap (priority queue in Java) to keep track of the k largest elements. The smallest element in this heap will be the kth largest element in the stream:
import java.util.PriorityQueue;
class KthLargest {
private final PriorityQueue<Integer> minHeap;
private final int k;
public KthLargest(int k, int[] nums) {
this.k = k;
this.minHeap = new PriorityQueue<>(k);
for (int num : nums) {
add(num);
}
}
public int add(int val) {
if (minHeap.size() < k) {
minHeap.offer(val);
} else if (val > minHeap.peek()) {
minHeap.poll();
minHeap.offer(val);
}
return minHeap.peek();
}
}
nums
.Thus, each add
operation is efficient, and we maintain the k-largest elements in O(log k) time per addition.
If there are any more questions or adjustments needed, feel free to ask!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?