347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note: 

    • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
    • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.


计算frequency,用map

找K个最值,用priority queue。这里是K个最大值,需要建一个min-heap,维持其大小不超过K。

 1 struct pairCompare{
 2     bool operator()(pair<int,int>&p1, pair<int,int>&p2){
 3         return p1.first>p2.first;
 4     }
 5 };
 6 
 7 class Solution {
 8 public:
 9     vector<int> topKFrequent(vector<int>& nums, int k) {
10         unordered_map<int,int> map; //calculate frequency
11         for(int num: nums){
12             map[num]++;
13         }
14         vector<int> result;
15 
16         //heap in C++ by default using less as a max-heap
17         //need a min-heap here (for k largest values)
18         priority_queue<pair<int,int>,vector<pair<int,int>>,pairCompare> pq; 
19         for(auto const it: map){
20             int key = it.first;
21             int val = it.second;
22             if(pq.size()<k){
23                 pq.push(make_pair(val,key));
24             }else{
25                 if(val>pq.top().first){
26                     pq.pop();
27                     pq.push(make_pair(val,key));
28                 }
29             }
30         }
31         
32         //loop all elements in the min-heap
33         while(!pq.empty()){
34             result.push_back(pq.top().second);
35             pq.pop();
36         }
37         
38         return result;
39     }
40 };

 

posted @ 2018-07-05 04:53  回到明天  阅读(90)  评论(0编辑  收藏  举报