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.
思路:建立hashmap记录val-count, 然后建立val-count的优先队列(以count值排序),然后吐出前k个pair对应first值即可。
struct cmp
{
bool operator() (const pair<int, int> a, const pair<int, int>b) const
{
return a.second < b.second;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> mymap;
for (int i = 0; i < nums.size(); i++){
if (mymap.find(nums[i]) != mymap.end()){
mymap[nums[i]]++;
}
else{
mymap[nums[i]] = 1;
}
}
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> myqueue(mymap.begin(), mymap.end());
vector<int> res(k, 0);
for (int i = 0; i < k; i++){
res[i] = myqueue.top().first;
myqueue.pop();
}
return res;
}
};