前 K 个高频元素
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/hash-table/xxwb2v/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int>ans;
unordered_map<int,int>hashmap;
for(auto u:nums){
hashmap[u]++;
}
int cnt=1;
for(auto it=hashmap.begin();it!=hashmap.end();++it){
if((it->second)>=cnt){
cnt=it->second;
}
}
while(k){
for(auto it=hashmap.begin();it!=hashmap.end();++it){
if((it->second)==cnt){
ans.push_back(it->first);
k--;
}
}
cnt--;
}
return ans;
}
};