1. 程式人生 > >leetcode692+出現次數做多的K單詞,優先佇列,注意重寫排序語法

leetcode692+出現次數做多的K單詞,優先佇列,注意重寫排序語法

https://leetcode.com/problems/top-k-frequent-words/description/

struct cmp{
    bool operator()(pair<int,string>a, pair<int, string>b)
    {
        if(a.first==b.first) return a.second>b.second;
        return a.first<b.first;
    }
};

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> m;
        priority_queue<pair<int, string>, vector<pair<int, string>>, cmp> Q;
        vector<string> res;
        for(auto a:words) ++m[a];
        for(auto it: m) Q.push({it.second, it.first});
        for(int i=0; i<k; i++){
            res.push_back(Q.top().second);
            Q.pop();
        }
        return res;
    }
};