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:
- You may assume k is always valid, 1 ? k ? number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
1 class Solution { 2 public: 3 vector<int> topKFrequent(vector<int>& nums, int k) { 4 map<int, int> m; 5 map<int, int>::iterator ite; 6 for (int i = 0; i < nums.size(); i++) 7 { 8 m[nums[i]]++; 9 } 10 vector<int> vet; 11 int max = INT_MIN; 12 int max1 = 0; 13 while (k) 14 { 15 int count = 0; 16 for (ite = m.begin(); ite != m.end(); ite++) 17 { 18 if (ite->second > max) 19 { 20 max = ite->second; 21 max1 = ite->first; 22 count++; 23 } 24 } 25 m[max1] = INT_MIN; 26 if (count != 0) 27 { 28 vet.push_back(max1); 29 } 30 max = INT_MIN; 31 k--; 32 } 33 return vet; 34 } 35 };