Lintcode 545. Top K Large Numbers II
Title description: Implement a data structure and provide the following two interfaces
- add(number) add an element
- topk() returns the top K number
The code uses priority_queue to store the largest number of K to achieve:
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;
}
};