LeetCode 703. Kth Largest Element in a Stream
考点 | 难度 |
---|---|
Tree | Easy |
题目
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:
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.
思路
用minheap,当heap的长度大于k
就pop
出数字,保证heap里的最小值是kth largest number。
答案
class KthLargest {
private static int k;
private PriorityQueue<Integer> heap;
public KthLargest(int k, int[] nums) {
this.k = k;
heap = new PriorityQueue<>();
for (int num: nums) {
heap.offer(num);
}
while (heap.size() > k) {
heap.poll();
}
}
public int add(int val) {
heap.offer(val);
if (heap.size() > k) {
heap.poll();
}
return heap.peek();
}
}