clueless coding // TODO: be smarter

LeetCode Top K Frequent Words: CPP Solution



TL;DR Code Solution


vector<string> topKFrequent(vector<string>& words, int k) {

    unordered_map<string, int> map;
    for (int i = 0; i < words.size(); i++) {
        map[words[i]]++;
    }

    auto cmp = [&map](string& a, string& b) { return map[a] > map[b] || (map[a] == map[b] && a < b); };
    std::priority_queue<string, vector<string>, decltype(cmp)> q3(cmp);

    vector<string> result;

    for (unordered_map<string, int>::iterator it = map.begin(); it != map.end(); it++) {
        q3.push(it->first);
        if (q3.size() > k) {
            q3.pop();
        }
    }

    while (!q3.empty()) {
        result.insert(result.begin(), q3.top());
        q3.pop();
    }

    return result;

}