地址:https://leetcode.com/problems/kth-largest-element-in-a-stream/
描述:
Design a class to find the k
th largest element in a stream. Note that it is the k
th largest element in the sorted order, not the k
th 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
Note:
You may assume that nums’ length ≥ k-1
and k
≥ 1.
理解:
返回输入的流中第k
大的数
思路:
自己想到的是用vector<int> maxK
做,初始化的时候对输入的数组排序,并把前k
大的存起来,然后再加入的时候如果在前k
个里就更新前k
大数组,否则就不更新,每次返回maxK.back()
。代码如下
class KthLargest {
vector<int> maxK;
public:
KthLargest(int k, vector<int> nums):maxK(k) {
sort(nums.begin(), nums.end(), [](int a, int b) {return a > b; });
for (int i = 0; i < k; ++i) {
maxK[i] = nums[i];
}
}
int add(int val) {
if (val > maxK.back()) {
int i;
for (i = maxK.size() - 1; i >= 0 && maxK[i] < val; --i) {
maxK[i] = i - 1 >= 0 ? maxK[i - 1] : val;
}
maxK[i+1] = val;
}
return maxK.back();
}
};
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
这样在nums.size()>=k
的时候应该没有问题,但是如果初始nums.size()<k
就会出错。懒得再去判断这种情况了。参考了别人的解法,使用了C++的priority_queue
.
解法:
priority_queue
允许为队列中的元素建立优先级。新加入的元素会排在所有优先级比它低的已有元素之前。默认基于vector
实现。- 底层采用堆实现。队首元素为优先级最高的元素。
默认优先级是从大到小。使用top()
获取优先级最高的元素。push()
和pop()
分别添加和删除。删除的为优先级最高的元素。
priority_queue<int> pq;
也可自定义优先级
priority_queue<int, vector<int>, less<int> > pq;
//其中,第二个参数( vector ),是来承载底层数据结构堆的容器;
//第三个参数( less ),则是一个比较类,less 表示数字大的优先级高,而 greater 表示数字小的优先级高。
//也就是说,less还是表示从大到小,greater则表示从小到大
参考: https://blog.csdn.net/lym940928/article/details/81239893
具体实现如下:
class KthLargest {
priority_queue<int, vector<int>, greater<int> > pq;
int k;
public:
KthLargest(int k, vector<int> nums):k(k) {
for (auto n : nums) {
pq.push(n);
if (pq.size() > k)
pq.pop();
}
}
int add(int val) {
pq.push(val);
if (pq.size() > k)
pq.pop();
return pq.top();
}
};
去和本科室友吃饭。