STL-priority_queue

347. Top K Frequent Elements

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;
}
};
1. unordered_map < int, int > //value初始为0

2. 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 >() > //改为从小到大

• 本文已收录于以下专栏：

举报原因： 您举报文章：STL-priority_queue 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)