zoukankan      html  css  js  c++  java
  • leetcode 347前k个高频元素

    通过hash map遍历一遍存储出现的次数,通过小顶堆存储k个元素

    //设想利用hash map来存储每个元素的个数;采用小顶堆存储k个元素;timeO(n+klogk)spaceO(n+k)
    
    class Solution {
    public:
        
        
        vector<int> topKFrequent(vector<int>& nums, int k) {
            if(nums.size()==0) return{};
            vector<int> res;
            unordered_map<int,int> m;
            for(int num:nums){
                m[num]++;
            }
            struct cmp{
                bool operator()(pair<int,int> a,pair<int,int> b) {return a.second>b.second;}//大于才是小顶堆
            };
            priority_queue<pair<int,int>,vector<pair<int,int> >,cmp> q;
            for(auto it:m){
                int num=it.first;
                //cout<<it.first<<",  "<<it.second<<endl;
                if(q.size()<k){
                    q.push(it);continue;
                }
                //cout<<it.first<<","<<it.second<<endl;
                //cout<<q.top().first<<","<<q.top().second<<endl;
                if(it.second>q.top().second){
                    q.pop();q.push(it);
                }
            }
            while(!q.empty()){
                res.push_back(q.top().first);
                q.pop();
            }
            return res;
        }
    };
  • 相关阅读:
    nginx公网IP无法访问浏览器
    Internet接入方式
    Adobe Photoshop Lightroom 5.3和序列号
    getopt
    printf
    scanf
    cycling -avoid the vicious cycle
    ACE handle_timeout 事件重入
    Linux查看程序端口占用
    The GNU C Library
  • 原文地址:https://www.cnblogs.com/joelwang/p/10932931.html
Copyright © 2011-2022 走看看