https://leetcode-cn.com/problems/top-k-frequent-words/
class Solution {
public:
class cmp
{
public:
bool operator()(const pair<string, int>& lhs, const pair<string, int>& rhs)
{
return lhs.second == rhs.second ? lhs.first < rhs.first : lhs.second > rhs.second;//注意这个地方,出现频率相同按字母排序
// return lhs.second > rhs.second;
}
};
vector<string> topKFrequent(vector<string>& words, int k)
{
unordered_map<string, int> mp;
for (auto& x: words)
{
mp[x]++;
}
//小顶堆 priority_queue
priority_queue<pair<string, int>, vector<pair<string, int>>, cmp> prq;
for (auto& y : mp)
{
// prq.emplace(y);
prq.push(y);
if (prq.size() > k)
prq.pop();
}
vector<string> res(k);
for (int i = k - 1; i >= 0; i--)
{
res[i] = prq.top().first;
prq.pop();
}
return res;
}
};