仔细分析TOP K元素问题

给出一个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;

    }

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值