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.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
Example:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
思路1
保存前k个最大的值——》sorted
用快排排序,复杂度也至少Nklogk
思路2
使用min heap 小顶堆, size = k
每次拿新的数和堆顶比较,如果新元素大,则删除堆顶把新元素加进来。
复杂度:NlogK(堆的维护时间)
#include <iostream>
#include <queue>
class KthLargest {
private:
std::priority_queue<int, std::vector<int>, std::greater<int> > pq; // 小顶堆
int size;
public:
KthLargest(int k, std::vector<int>& nums) {
size = k;
for(auto number : nums) {
add(number);
}
}
int add(int val) {
if (size > pq.size()) {
pq.push(val);
return pq.top();
}
if (val > pq.top()) {
pq.pop();
pq.push(val);
}
return pq.top();
}
};
#include <iostream>
#include "KthLargest.cpp"
#include <vector>
int main() {
std::vector<int> nums = { 4, 5, 8, 2};
KthLargest *kthlargest = new KthLargest(3, nums);
int newNum;
while (std::cin >> newNum) {
std::cout << kthlargest->add(newNum);
}
}