347.前 K 个高频元素
学会了怎么构建和使用优先队列后这题就比较简单了。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
for(int i = 0; i < nums.size(); i++ )
{
map[ nums[i] ]++;
}
//比较函数返回true时,表示第一个参数应该排在第二个参数的前面。估计源码里STL队首是指向优先级最后。记住就行
auto cmp = [](const pair<int, int>& a, const pair<int,int>& b)
{
return a.second > b.second;
};
//构建并维护一个大小为k的小顶堆,频率最低的元素会在堆顶。
std::priority_queue< pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pri_que(cmp);
for( auto it = map.begin(); it != map.end(); it++ )
{
pri_que.push( *it );
if(pri_que.size() > k)
{
pri_que.pop();
}
}
vector<int> result(k);
for(auto i = k - 1; i >= 0; i--)
{
result[i] = pri_que.top().first;
pri_que.pop();
}
return result;
}
};

浙公网安备 33010602011771号