参考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初始为0priority_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 >() > //改为从小到大
本文介绍了一种使用C++标准库中的优先队列(priority_queue)来实现寻找数组中最常出现的Top K元素的方法。通过结合哈希表(unordered_map)统计每个元素的频率,并利用优先队列自动维护最大堆特性,从而高效地找到频率最高的前K个元素。

1163

被折叠的 条评论
为什么被折叠?



