[LeetCode347]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.
分类:Hash Table Heap
代码:
1 class Solution { 2 public: 3 vector<int> topKFrequent(vector<int>& nums, int k) { 4 unordered_map<int,int> hash; 5 /* 6 for(int i = 0; i < nums.size(); ++i) 7 { 8 auto ret = hash.insert({nums[i],1}); 9 if(!ret.second)//如果已经存在 10 { 11 ++ret.first->second; 12 } 13 } 14 */ 15 for(auto num : nums) 16 ++hash[num]; 17 18 //利用堆排序实现 19 priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq; 20 for(auto m : hash) 21 { 22 pq.push({m.second,m.first}); 23 if(pq.size() > k) 24 pq.pop(); 25 } 26 27 //现在根据出现次数元素已经在堆中排好序了 28 vector<int> res; 29 while(!pq.empty()) 30 { 31 res.push_back(pq.top().second); 32 pq.pop(); 33 } 34 reverse(res.begin(),res.end()); 35 return res; 36 } 37 };