LeetCode347_TopK

利用map先统计一下元素的频率;

利用优先队列,求前K大频率,注意使用最小堆(维护一个元素个数k个的最小堆);

重新设置比较器为greater,即最小堆。因为优先队列默认是最大堆less;

另外对于队列元素是pair,需要了解比较规则为先比较first再比较second;

 1 // 347. Top K Frequent Elements
 2 // https://leetcode.com/problems/top-k-frequent-elements/description/
 3 // 时间复杂度: O(nlogk)
 4 // 空间复杂度: O(n + k)
 5 class Solution {
 6 public:
 7     vector<int> topKFrequent(vector<int>& nums, int k) {
 8         unordered_map<int,int> freq; //元素-频率
 9         for(int i = 0; i<nums.size(); i++){
10             freq[nums[i]]++;
11         }
12         //要用到最小堆,C++默认是最大堆less
13         priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
14         for(unordered_map<int,int>::iterator itr = freq.begin(); itr != freq.end(); itr++){
15             if(pq.size()==k){
16                 if(itr->second > pq.top().first){
17                     pq.pop();
18                     pq.push(make_pair(itr->second,itr->first));
19                 }
20             }
21             else {
22                 pq.push(make_pair(itr->second,itr->first));
23             }
24         }
25         vector<int> res;
26         while(!pq.empty()){
27             res.push_back(pq.top().second);
28             pq.pop();
29         }
30         return  res;
31     }
32 };

猜你喜欢

转载自www.cnblogs.com/grooovvve/p/12367281.html
347