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实质上也是用堆排序完成的。
高效的找出数组中出现频率最高的K个元素

该问题要求在非空整数数组中找到出现频率最高的k个元素。解决方案可以采用映射结合最小堆的方法,同时需要自定义比较方式以确保堆中的元素是按频率降序排列。
838

被折叠的 条评论
为什么被折叠?



