描述
设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。
请实现 KthLargest 类:
KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。
分析
第1大是最大的那个数,第2大是仅次于最大的那个数,依此类推,第K大是从大到小排序,第K个元素就是第K大。
class KthLargest {
PriorityQueue<Integer> heap;
int len;
public KthLargest(int k, int[] nums) {
heap = new PriorityQueue<>();
for(int num : nums){
heap.offer(num);
if(heap.size() > k){
heap.poll();
}
}
len = k;
}
public int add(int val) {
heap.add(val);
if(heap.size() > len){
heap.poll();
}
return heap.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/