赞
踩
- #include <iostream>
- #include <vector>
- #include <unordered_map>
- #include <queue>
- #include <algorithm>
- using namespace std;
- vector<int> count(vector<int> nums,int k)
- {
- unordered_map<int,int> map;//key
- //举例:nums:1 1 1 2 2 3
- for(auto num:nums)
- {
- map[num]++; //统计map[1]、map[2]、map[3]的个数
- }
- vector<int> res;
- priority_queue<pair<int,int> > pq;//满足先进先出,主要是队头出来,队尾插入数据
- for(auto it=map.begin();it!=map.end();it++){
- pq.push(make_pair(it->second,it->first ));//按照频率排列(默认是less,从大到小)
- if(pq.size()>(int)map.size()-k){
- res.push_back(pq.top().second);
- pq.pop();
- }
- }
- return res;
- }
- int main() {
-
- int n;
- vector<int> arr={1,1,1,2,2,3};//test
- int k=2;
- vector<int> res=count(arr,k);
- sort(res.begin(),res.end());
- for(auto x:res){
- cout<<x<<" ";
- }
- cout<<endl;
- return 0;
- }
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。