其他不多赘述,代码也写得很抽象就不谈了。主要是priority_queue定义时候要传入一个自定义比较器。比较器应该是个类型(而不是这个类型的实例吧),所以模板里面不能填一个lambda表达式的变量。但是可以用c++11的decltype获得这个表达式的类型,在初始化priority_queue时通过括号传入。
class Solution {
public:
unordered_map<int,int> xcounts;
// struct cmp{
// unordered_map<int, int>& counts;
// cmp(unordered_map<int, int>& counts_) : counts(counts_) {}
// bool operator()(int a, int b){ return counts[a]>counts[b]; };
// };
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
xcounts.clear();
// for(auto i:xcounts) cout<<i.first<<" "<<i.second<<endl;
auto cmp = [&](int a, int b) { return xcounts[a] > xcounts[b]; };
priority_queue<int,vector<int>,decltype(cmp)> pq(cmp);
for(int j=0;j<nums.size();++j){
int i=nums[j];
// cout<<i<<" ";
if(xcounts.find(i)!=xcounts.end()) xcounts[i]++;
else xcounts[i]=1;
}
int pqTmpLen=0;
for(auto i=xcounts.begin();i!=xcounts.end();i++)
{
// cout<<i->first<<" "<<i->second<<endl;
if(pqTmpLen<k)
{
pq.push(i->first);
pqTmpLen++;
}
else{
if(xcounts[pq.top()]<xcounts[i->first]){
pq.pop();
pq.push(i->first);
}
}
// cout<<pq.top()<<endl;
}
vector<int>res(k,0);
int i=0;
while(!pq.empty())
{
res[i++]=pq.top();
pq.pop();
}
return res;
}
};