给出一个List让你找出词频最高的前K个数字,首先想到的就是优先队列嘛因为如果要从一个更大的数组里筛选小的数组,优先队列肯定需要考虑因为优先队列内部自动排序的特性。
接下来就是如何定义一个class让这个队列排列成我们想要的形状,我们以第二个元素进行排序,每当我们发现这个列队满了的时候,便比较这个元素和我们队列中最不频繁的元素即可,如果这个数字比最不频繁的元素出现还少,那肯定排除,反之亦然。
Tips:优先队列默认大顶堆,也就是都是以>进行排序,前面一个元素大于后面一个元素,因为优先队列是看队尾的,所以top为根据定义的最小元素
class Solution {
public:
struct cmp{
bool operator()(const pair<int,int> &a, const pair<int,int> &b){
return a.second>b.second;//递减,top就是词频最小的那个
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
priority_queue<pair<int,int>,vector<pair<int,int>>,cmp>pq2fre;
unordered_map<int,int>word2fre;
for(int i = 0; i < nums.size();i++){
word2fre[nums[i]]++;
}
for(auto [num,counts]: word2fre){
cout << counts << endl;
if(pq2fre.size() < k){
pq2fre.push({num,counts});
}
else{
if(pq2fre.top().second < counts){
pq2fre.pop();
pair<int,int>p1(num,counts);
pq2fre.push(p1);
}
}
}
vector<int>ans;
while(!pq2fre.empty()){
ans.push_back(pq2fre.top().first);
pq2fre.pop();
}
return ans;
}
};