clueless coding // TODO: be smarter

LeetCode Top K Frequent Elements: CPP Solution



TL;DR Code Solution


vector<int> topKFrequent(vector<int>& nums, int k) {

    unordered_map<int, int> freqs;
    vector<int> result;

    for (int num : nums) {
        freqs[num]++;
    }

    auto cmp = [&freqs](int& a, int& b) {
        return freqs[a] > freqs[b] || (freqs[a] == freqs[b] && a < b);
    };
    priority_queue<int, vector<int>, decltype(cmp)> pq(cmp);

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

    while (!pq.empty()) {
        result.push_back(pq.top());
        pq.pop();
    }

    return result;


}