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; } };