描述
给定一个非空的整数数组,返回其中出现频率前 k 高的元素
解法
class Solution
{
public:
std::vector topKFrequent(std::vector &nums, int k)
{
std::map<int, int> val2cnt;
for (const auto &i : nums)
{
if (val2cnt.find(i) == val2cnt.end())
val2cnt[i] = 1;
else
++val2cnt[i];
}
auto compareFun = { return lhs.second > rhs.second; };
std::priorityqueue<std::pair<int, int>, std::vector<std::pair<int, int>>, decltype(compareFun)> heap(compareFun);
for (auto &i : val2cnt)
{
if (heap.size() != k)
heap.push(i);
else
{
auto cur = heap.top();
if (cur.second < i.second)
{
heap.pop();
heap.push(i);
}
}
}
std::vector ans;
while (!heap.empty())
{
auto cur = heap.top();
ans.pushback(cur.first);
heap.pop();
}
return ans;
}
};