您的位置:首页 > 产品设计 > UI/UE

LeetCode 692. Top K Frequent Words

2017-12-23 13:00 330 查看
题目链接:https://leetcode.com/problems/top-k-frequent-words/description/

template<class _Ty1, class _Ty2>
struct MyPairLess {
typedef _Ty1 first_argument_type;
typedef _Ty2 second_argument_type;
typedef bool result_type;
constexpr bool operator() (const pair<_Ty1, _Ty2>& lhs, const pair<_Ty1, _Ty2>& rhs) const {
return lhs.first < rhs.first ||
(!(rhs.first < lhs.first) && lhs.second > rhs.second);
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
vector<string> res;
priority_queue < pair<int, std::string>,
vector<pair<int, std::string>>,
MyPairLess<int, std::string> > pq;
unordered_map<std::string, int> hash;
for (std::string s : words)
hash[s]++;
for (auto it = hash.begin(); it != hash.end(); ++it)
pq.push(make_pair(it->second, it->first));
for (int i = 0; i < k; ++i) {
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: