算法1
注意下双关键字排序
C++ 代码
typedef pair<int,string> PIS;
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
vector<string>ans(k);
unordered_map<string,int>hash;
for(auto &c : words)hash[c] ++;
priority_queue<PIS>pq;
for(auto &c : hash){
pq.push({-c.second,c.first});
if(pq.size() > k)pq.pop();
}
for(int i = k-1; i>= 0;--i){
ans[i] = pq.top().second;
pq.pop();
}
return ans;
}
};