【题目描述】
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.
【解题思路】
先用哈希表扫描一遍,然后用最大堆来求出最大的k个值
【代码】
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int sz=nums.size();
vector<int> vec;
if(sz==0) return vec;
map<int,int> m;
priority_queue<pair<int, int> >pq;
for(int i=0;i<sz;i++){
m[nums[i]]++;
}
map<int, int>::iterator iter;
for(iter=m.begin();iter!=m.end();iter++){
pq.push(make_pair(iter->second,iter->first));
}
while(k--){
vec.push_back(pq.top().second);
pq.pop();
}
return vec;
}
};
本文介绍了一种高效算法,用于从整数数组中找出出现频率最高的k个元素。该算法首先利用哈希表统计每个元素的出现次数,然后借助最大堆筛选出前k个最频繁的元素。
869

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



