题目:给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
eg:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
eg:
输入: nums = [1], k = 1
输出: [1]
提示:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
你可以按任意顺序返回答案。
代码思路:首先用unordered_map()进行映射,记录每次出现的值,
然后用优先队列,进行k项插值。
然后输出 。如此的简介明了。
注意里面的unordered_map的使用,他可以直接用key作为索引,非常的方便,查找非常的快速。
同时priority_queue的使用也要注意一下,可以看https://blog.csdn.net/id145/article/details/107659229
最后稍微注意一下他们插值用的是emplace(),和emplace_back()来代替push和push_back();
他们是可以直接接受元素的,直接在容器里面进行构造。减少了拷贝。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> Result;
unordered_map<int, int> Map;
int Size = nums.size();
for (auto i:nums)
{
Map[i]++;
}
//有限队列,大堆顶,用pair<int,int> 作为参数
//先比较第一元素,第一个元素相等比较第二个元素
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pqueue;
//遍历整个Map 方法1
//unordered_map<int, int>::iterator it = Map.begin();
//for ( ; it !=Map.end(); it++)
//{
// pqueue.emplace(i.second, i.first);
// if (pqueue.size() > k)
// {
// pqueue.pop();
// }
//}
//遍历整个Map 方法2
for (auto& i : Map)
{
//i.first 是key ,i.second 是unordered_map()的value
pqueue.emplace(i.second,i.first);
//pqueue.push(pair<int,int>(i.second, i.first));
if (pqueue.size()>k)
{
pqueue.pop();
}
}
while (!pqueue.empty())
{
Result.emplace_back(pqueue.top().second);
pqueue.pop();
}
return Result;
}
};