LeetCode 692. Top K Frequent Words

来源:互联网 发布:工业设计软件图标 编辑:程序博客网 时间:2024/06/05 12:47

题目链接: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;    }};
原创粉丝点击