240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 16 | Leetcode 692. Top K Frequent Words

题解

Medium

Heap (Priority Queue)

难点是自己写comparator。

class comparator {
public:
    bool operator() (const pair<string, int>& a, const pair<string, int>& b) const {
        if(a.second == b.second) return a.first > b.first;
        return a.second < b.second;
    }
};

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> m;
        
        for(string word : words) {
            m[word]++;
        }
        
        priority_queue<pair<string, int>, vector<pair<string, int>>, comparator> pq;
        
        for(auto item : m) {
            pq.push(item);
        }
        
        vector<string> ret;

        for(int i = 0; i < k; i++) {
            auto t = pq.top();
            pq.pop();
            ret.push_back(t.first);
        }
        
        return ret;
        
    }
};
posted @ 2020-10-01 06:50  CasperWin  阅读(88)  评论(0编辑  收藏  举报