您的位置:首页 > 产品设计 > UI/UE

Top K Frequent Elements

2016-05-11 10:18 330 查看
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实质上也是用堆排序完成的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: