Kth Largest Element in a Stream 数据流中的第 K 大元素
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) Returns the element representing the kth largest element in the stream.
Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]
思路
可以通过小顶堆,将所有数字入堆,维持堆的大小为k。
此时堆顶元素为所求的结果
public PriorityQueue<Integer> pq;
public int _k;
public KthLargest(int k, int[] nums) {
pq = new PriorityQueue<>((o1,o2)->o1-o2);
_k = k;
for (int num : nums) {
add(num);
}
}
public int add(int val) {
pq.offer(val);
if(pq.size()>_k){
pq.poll();
}
return pq.peek();
}
Tag
heap