LeetCode_Heap_703. Kth Largest Element in a Stream 数据流中的第 K 大元素 【堆】【C++/java】【简单】
原创
©著作权归作者所有:来自51CTO博客作者再见萤火虫IT的原创作品,请联系作者获取转载授权,否则将追究法律责任
目录
一,题目描述
英文描述
中文描述
示例与说明
二,解题思路
三,AC代码
C++
Java
四,解题过程
第一博
一,题目描述
英文描述
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.
中文描述
设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。
请实现 KthLargest 类:
KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。
示例与说明
(题目数据保证,在查找第 k 大元素时,数组中至少有 k 个元素)
二,解题思路
第K个最大值理论上有两种思路:
1,把所有数据放进大根堆里,然后pop出k-1个元素,取堆顶元素。但由于本题中堆的数据是不断改变的,所以此方法不行;
2,维持一个大小为k的小根堆,当堆的size达到k时,每加入一个数据需要先和堆顶元素比较,大于堆顶才能push,然后弹出堆顶即可;
三,AC代码
C++
class KthLargest {
public:
// 这里的greater可以理解为堆中的元素越来越大,因此是小根堆
priority_queue<int, vector<int>, greater<int>> queue;
int k;
KthLargest(int k, vector<int>& nums) {
this->k = k;
for (int i = 0; i < nums.size(); i++) {
if (queue.size() < k) queue.push(nums[i]);
else if (queue.top() < nums[i]) {
queue.push(nums[i]);
queue.pop();
}
}
}
int add(int val) {
if (queue.size() < k) queue.push(val);
else if (queue.top() < val) {
queue.push(val);
queue.pop();
}
return queue.top();
}
};
Java
class KthLargest {
PriorityQueue<Integer> queue;
int k;
public KthLargest(int k, int[] nums) {
this.k = k;
queue = new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer x, Integer y) {
return x - y;
}
});
// 也可以这样实现
// PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> a - b);
for (int i = 0; i < nums.length; i++) {
if (queue.size() < k) queue.offer(nums[i]);
else if (nums[i] > queue.peek()) {
queue.offer(nums[i]);
queue.poll();
}
}
}
public int add(int val) {
if (queue.size() < this.k) {
queue.offer(val);
} else if (val > queue.peek()) {
queue.offer(val);
queue.poll();
}
return queue.size() == 0 ? null : queue.peek();
}
}
四,解题过程
第一博