标签:
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
Subscribe to see which companies asked this question
20 / 20 test cases passed.
|
Status:
Accepted |
Runtime: 56 ms
|
1 struct PP 2 { 3 int val; 4 int count; 5 }te; 6 7 bool cmp(PP a,PP b) 8 { 9 return a.count > b.count; 10 } 11 12 class Solution { 13 public: 14 vector<int> topKFrequent(vector<int>& nums, int k) { 15 int n = nums.size(); 16 vector<int> ans; 17 vector<PP> temp; 18 map<int,int> mp; 19 int i; 20 for(i = 0;i < n;i++){ 21 mp[ nums[i] ]++; 22 } 23 for(map<int,int>::iterator it = mp.begin();it != mp.end();it++){ 24 te.val = it -> first; 25 te.count = it -> second; 26 temp.push_back(te); 27 } 28 sort(temp.begin(),temp.end(),cmp); 29 for(i = 0;i < k;i++){ 30 ans.push_back(temp[i].val); 31 } 32 return ans; 33 } 34 };
leetcode 347. Top K Frequent Elements
标签:
原文地址:http://www.cnblogs.com/njczy2010/p/5454233.html