自定义优先队列比较的元素(LC692 Top K Frequent Words为例)
作者:
格莱
,
2020-01-02 03:15:53
,
所有人可见
,
阅读 961
692. Top K Frequent Words
class Solution {
typedef pair<string, int> tp;
public:
struct cmp {
bool operator()(const tp &a, const tp &b) const{
if(a.second < b.second) return true;
else if(a.second == b.second) {
int t = strcmp(a.first.c_str(), b.first.c_str());
if(t < 0) return false;
else return true;
} else {
return false;
}
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> wtf;
vector<string> res;
for(auto w: words) {
if(wtf[w]) wtf[w]++;
else wtf[w] = 1;
}
priority_queue<tp, vector<tp>, cmp> pq;
for(auto i = wtf.begin(); i != wtf.end(); i++) {
pq.push(make_pair(i->first, i->second));
}
for(int i = 0; i < k; i++) {
res.push_back(pq.top().first);
pq.pop();
}
return res;
}
};