解法一:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
priority_queue<pair<int, int>> q;
vector<int> res;
for (auto a : nums) ++m[a];
for (auto it : m) q.push({it.second, it.first});
for (int i = 0; i < k; ++i) {
res.push_back(q.top().second); q.pop();
}
return res;
}
};
解法二:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> temp;
vector<vector<int>> bucket(nums.size()+1);
vector<int> res;
for(int a:nums) temp[a]++;
for(auto a: temp){
bucket[a.second].push_back(a.first);
}
for(int i=nums.size();i>=0;i--){
for(int j=0;j<bucket[i].size();j++){
res.push_back(bucket[i][j]);
if(res.size()==k) return res;
}
}
}
};
两种解法唯一的不同点就是分别用priority_queue和bucket来存hash_map的数据。
priority_queue存入需要O(N logN), bucket存入需要O(N),取出数据两者都是O(k)
space?