Leetcode 347. 前k个高频元素。

 其他不多赘述,代码也写得很抽象就不谈了。主要是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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值