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.
map加最小堆。
需要新定义比较方法。
class Solution {
struct cmp {
bool operator() (const pair<int,int> &a, const pair<int,int> &b)
{
return a.second>b.second;
}
};
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> ret;
unordered_map<int ,int > Hash;
for(int i=0; i<nums.size(); ++i){
Hash[nums[i]]++;
}
priority_queue<pair<int ,int>,vector<pair<int,int>>,cmp> PQ;
for(auto i = Hash.begin(); i != Hash.end(); ++i){
if(PQ.size()!=k){
PQ.push(*i);
}
else{
if(i->second>PQ.top().second){
PQ.pop();
PQ.push(*i);
}
}
}
while(!PQ.empty()){
ret.push_back(PQ.top().first);
PQ.pop();
}
reverse(ret.begin(),ret.end());
return ret;
}
};
stl库中有partial_sort实质上也是用堆排序完成的。