进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。
1. 堆 / 优先队列
cpp
class Solution {
public:
struct cmp{
bool operator() (const pair<int,int>& a, const pair<int,int>& b){
return a.second > b.second; // 小顶堆
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> count;
for(auto x: nums) count[x]++;
// pair 的第一个元素代表数组的值,第二个元素代表了该值出现的次数
priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> q;
for(auto x: count){
int num = x.first;
int cnt = x.second;
if(q.size()==k){
if(q.top().second < cnt){
q.pop();
q.push({num,cnt});
}
}
else{
q.push({num,cnt});
}
}
vector<int> res;
while(!q.empty()){
int num = q.top().first;
res.push_back(num);
q.pop();
}
return res;
}
};