Skip to content

Latest commit

 

History

History
40 lines (29 loc) · 916 Bytes

692. Top K Frequent Words.md

File metadata and controls

40 lines (29 loc) · 916 Bytes
class Solution {
public:
    typedef pair<string, int> Node;
    
    vector<string> topKFrequent(vector<string>& words, int k) {
        
        unordered_map<string, int> count;
        
        for (const string& word : words) {
            count[word]++;
        }
        
        auto comp = [](const Node& a, const Node& b) {
            if (a.second == b.second)
                return a.first < b.first;
            return a.second > b.second;
        };
        
        priority_queue<Node, vector<Node>, decltype(comp)> q(comp);
        
        for (const auto& kv : count) {
            q.push(kv);
            if (q.size() > k) q.pop();
        }
        
        vector<string> ans;
        
        while (!q.empty()) {
            ans.push_back(q.top().first);
            q.pop();
        }
        
        std::reverse(ans.begin(), ans.end());
        return ans;
        
    }
};