347. 前K个高频元素
题目描述
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
说明:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
思路
对于元素出现的频率,可以使用一个哈希表来技术,之后便是找出哈希表中出现次数前k的元素,可以使用桶排序,也可以使用对排序
堆排序做法
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> hash;//哈希表记录出现次数
vector<int> res;
priority_queue<pair<int,int>> q;//存放哈希的堆,使用pair存放哈希的first,second
for(auto x:nums) hash[x]++;
for(auto it:hash) q.push({it.second,it.first});//second放前面,排序默认根据pair的第一个排序
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> m;
vector<vector<int>> bucket(nums.size() + 1);
vector<int> res;
for (auto a : nums) ++m[a];
for (auto it : m) {
bucket[it.second].push_back(it.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;
}
}
return res;
}
};
另一种写法,直接找k的下界,高于下界的就是答案
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> hash;
vector<int> res;
for(auto x:nums) hash[x]++;
int n=nums.size();
vector<int> s(n+1,0);
for(auto &p:hash) s[p.second]++;//放入桶中
int i=n,t=0;
while(t<k) t+=s[i--];
for(auto &p:hash)
if(p.second>i)
res.push_back(p.first);
return res;
}
};