前 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 个高频元素的集合是唯一的。
你可以按任意顺序返回答案。
思路:
- 对数组中的数的频率进行统计,可以使用unordered_map,key为数,value为频率。
- 对统计的频率进行排序,可以使用multimap,将其设为升序排序。此处要使用multimap,而非map,因为map会去重,而不同数其频率是可能相同的。
- 输出频率排在前k的数。
- 对于map与unordered_map区别与用法,参考链接1。
- 对于map与multimap区别与用法,参考链接2。
代码:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k)
//unordered_map统计各元素的出现次数
unordered_map<int,int> nums_count;
for(auto x:nums)
{
nums_count[x]++;
}
//小根堆统计出现次数前k的元素,不能为map,map会去重,而不同元素出现次数是可能一样的
multimap<int,int,greater<int>> big_m;
for(auto x:nums_count)
{
big_m.insert(make_pair(x.second,x.first));
}
//输出
vector<int> res;
for(auto it=big_m.begin();it!=big_m.end() && k; it++,k--)
{
res.push_back(it->second);
}
return res;
}
};
结果:
参考链接:
[1] Real_JumpChen:map和unordered_map的差别和使用
[2] yam_sunshine:map和multimap的用法详解
[3] 陈乐乐happy:leetcode前K个高频元素c++