参考http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/
most votes:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int num : nums){
map[num]++;
}
vector<int> res;
// pair<first, second>: first is frequency, second is number
priority_queue<pair<int,int>> pq;
for(auto it = map.begin(); it != map.end(); it++){
pq.push(make_pair(it->second, it->first));
if(pq.size() > (int)map.size() - k){
res.push_back(pq.top().second);
pq.pop();
}
}
return res;
}
};
unordered_map < int, int > //value初始为0
priority_queue < pair < int, int> >
【priority_queue】默认从大到小
top()
: return the greatest element.
pop()
: pop the greatest element.
【priority_queue排序】
默认的排序函数:
pair< int, int > 在pair中从第一个元素到最后一个元素为基排序
If you do not specify your own comparator, sorting is done by a built-in function compare. From first member to last member in pair. compare works for many types of values, ordering them in one particular way: increasing numeric order for numbers; lexicographic order (aka dictionary order) for strings, symbols, and keywords; shortest-to-longest order by Clojure vectors, with lexicographic ordering among equal length vectors.
priority_queue < int, vector < int >, greater< int >() > //改为从小到大