leetcode:前 K 个高频元素
/*
* @lc app=leetcode.cn id=347 lang=cpp
*
* [347] 前 K 个高频元素
*/
// @lc code=start
class Solution {
public:
// 小顶堆
class mycom {
public:
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second > rhs.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res;
unordered_map<int,int> map;
for(int curr : nums)
map[curr]++;
priority_queue<pair<int,int>,vector<pair<int,int>>,mycom> queue;
for(auto it = map.begin(); it!= map.end(); it++)
{
queue.push(*it);
if(queue.size() > k)
queue.pop();
}
for (int i = k - 1; i >= 0; i--) {
res.push_back(queue.top().first);
queue.pop();
}
return res;
}
};
// @lc code=end
priority_queue默认是大根堆,也就是大的元素会放在前面,如果要支持小根堆
- 自定义‘比较函数’,然后指定priority_queue的第三个参数
struct cmp
{
bool operator() (const T& t1, const T& t2)
{
return t1 > t2;
}
}
- 或者重载<或>操作符
//Overload the < operator
bool operator< (const T& t1, const T& t2)
{
return t1.x > t2.x;
}
//Overload the > operator
bool operator> (const T& t1, const T& t2)
{
return t1.x < t2.x;
}