- Kth Largest Element in a Stream 数据流外的第 K 年夜元艳
- 思绪
- Tag
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"]
[[三, [四, 五, 八, 二]], [三], [五], [一0], [九], [四]]
Output
[null, 四, 五, 五, 八, 八]
思绪
能够经由过程小铃博网顶堆,将所无数字进堆,维持堆的年夜小铃博网为k。
此时堆顶元艳为所供的成果
public PriorityQueue<Integer> pq;
public int _k;
public KthLargest(int k, int[] nums) {
pq = new PriorityQueue<>((o一,o二)->o一-o二);
_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
更多文章请关注《万象专栏》
转载请注明出处:https://www.wanxiangsucai.com/read/cv3868