Lintcode 545. 前K大数 II
题目描述:实现一个数据结构,提供下面两个接口
- add(number) 添加一个元素
- topk() 返回前K大的数
代码使用priority_queue一直存着最大的K个数进而来实现的:
bool cmp(const int &a, const int &b) {
return a > b;
}
class Solution {
private:
priority_queue<int, vector<int>, greater<int>> queue;
int k;
public:
/*
* @param k: An integer
*/Solution(int k) {
this->k = k;
}
/*
* @param num: Number to be added
* @return: nothing
*/
void add(int num) {
if (k > queue.size()) {
queue.push(num);
} else if (num > queue.top()){
queue.pop();
queue.push(num);
}
}
/*
* @return: Top k element
*/
vector<int> topk() {
vector<int> topk;
int n = queue.size();
for (int i = 0; i < k && i < n; ++i) {
topk.push_back(queue.top());
queue.pop();
}
for (int i = 0; i < n; ++i) {
queue.push(topk[i]);
}
sort(topk.begin(), topk.end(), cmp);
return topk;
}
};