Given a non-empty array of integers, return the k most frequent elements.
To solve this problem in linear time, we definitely need extra space. First, we use a hash map to calculate the frequency of each word, and then we put the words with same frequency in the same bucket. At last, traverse through all buckets until we have top k frequent elements.
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> tmp;
vector<int> res;
vector<vector<int>> bucket(nums.size() + 1);
for(auto num : nums) tmp[num]++;
for(auto i : tmp) bucket[i.second].push_back(i.first);
for(int i = bucket.size() - 1; i >= 0 && res.size() < k; i--)
for(int j = 0; j < bucket[i].size() && res.size() < k; j++)
res.push_back(bucket[i][j]);
return res;
}
};