主要是对次数进行排序,然后去前几个最大次数的值,输出即可
1 class Solution { 2 public: 3 vector<int> topKFrequent(vector<int>& nums, int k) { 4 int i; 5 unordered_map<int,int>p_map; 6 map<int,int>::iterator it; 7 for(i=0;i<nums.size();i++) { 8 p_map[nums[i]]++; 9 } 10 priority_queue<pair<int,int>>p_queue; 11 for(it=p_map.begin();it!=p_map.end();it++) 12 p_queue.push(make_pair(it->second,it->first)); 13 vector<int>num_result; 14 for(i=1;i<=k;i++) { 15 num_result.push_back(p_queue.top().second); 16 p_queue.pop(); 17 } 18 return num_result; 19 } 20 };
另一种写法也非常好:http://blog.csdn.net/yzhang6_10/article/details/51388021
1 class Op{ 2 public: 3 int Op_count; 4 int Op_num; 5 Op(int count,int num) { 6 Op_count=count; 7 Op_num=num; 8 } 9 bool operator <(const Op&Cpone)const 10 { 11 return Op_count>Cpone.Op_count; 12 } 13 }; 14 class Solution { 15 public: 16 vector<int> topKFrequent(vector<int>& nums, int k) { 17 int i; 18 map<int,int>p_map; 19 map<int,int>::iterator it; 20 for(i=0;i<nums.size();i++) { 21 p_map[nums[i]]++; 22 } 23 vector<Op>p_queue; 24 for(it=p_map.begin();it!=p_map.end();it++) 25 p_queue.push_back(Op(it->second,it->first)); 26 vector<int>num_result; 27 sort(p_queue.begin(),p_queue.end()); 28 for(i=0;i<k;i++) 29 num_result.push_back(p_queue[i].Op_num); 30 31 return num_result; 32 } 33 };