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.
这道题我用的是unordered_map,在不同的数都存下来之后 直接找最大值。(或者直接用桶排序也可以)
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> topk(k);
unordered_map<int,int> hash;
for (int i = 0; i < nums.size(); i++) {
unordered_map<int,int>::iterator has = hash.find(nums[i]);
if (has == hash.end()) hash[nums[i]] = 1;
else (*has).second += 1;
}
unordered_map<int,int>::iterator it = hash.begin();
int max = it->second;
int pos = it->first;
for (int i = 0; i < k; i++) {
for (it = hash.begin(); it != hash.end(); it++) {
if (it->second > max) {
max = it->second;
pos = it->first;
}
}
topk[i] = pos;
hash[pos] = 0;
max = 0;
pos = 0;
}
return topk;
}
};