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.
很常见的top-k问题,我一开始的想法就是用哈希表来实现。
注意priority_queue的使用,排序是first,所以把second放在first。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
priority_queue<pair<int, int>> pq;
vector<int> res;
int n = nums.size();
for (int i=0; i<n; i++) {
map[nums[i]]++;
}
for (auto iter=map.begin(); iter!=map.end(); iter++) {
pq.push(make_pair(iter->second, iter->first));
}
for (int i=0; i<k; i++) {
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};