347. Top K Frequent Elements
思路:
先建立hash表统计出现的次数. 然后使用桶排序, 按照次数丢入桶中. 时间复杂度O(n)
code:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> hash;
for (int i = 0; i < nums.size(); i++)
hash[nums[i]]++;
vector<list<int>> buckets(nums.size() + 1);
for (map<int, int>::iterator it = hash.begin(); it != hash.end(); ++it) // replace to auto
buckets[it->second].push_back(it->first);
vector<int> result;
for (int i = nums.size(); i >= 0 && result.size() < k; i--)
//for(list<int>::iterator it = buckets[i].begin(); it != buckets[i].end() ; it++) {
for (auto it : buckets[i]) { // STL auto since C++11
result.push_back(it);
if (result.size() == k)
break;
}
return result;
}
};