1.347. 前 K 个高频元素 - 力扣(LeetCode)
2.题目中前k个,就很明显的提示了我们这是堆的topk问题,所以要使用优先队列,而这种统计频率的题肯定要使用哈希表去重,所以用了unordered_map,由于优先队列默认是大堆,而我们要建大堆,但是元素不是简单的数据,而是pair的second进行比较,所以还是要采取(数据类型,存储容器,自定义比较类/比较函数)的格式
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int>map1;
for(auto a:nums)
{
map1[a]++;
}
struct t
{
bool operator()(pair<int,int>&p1,pair<int,int>&p2)
{
return p1.second>p2.second;
}
};
priority_queue<pair<int,int>,vector<pair<int,int>>,t>q;
for(auto& b:map1)
{
q.push(b);
if(q.size()>k)
{
q.pop();
}
}
vector<int>ret;
while(!q.empty())
{
ret.push_back(q.top().first);
q.pop();
}
return ret;
}
};