[C++] Simple solution using STL containers


  • 0
    Y

    In case you are lazy. And STL containers usually have better implementation than error-prone handwritten algorithms.

    class Solution {
    public:
        
        using pii = pair<int, int>;
        
        vector<int> topKFrequent(vector<int> &nums, int k) {
            
            // initializes the dictionary for counting elements
            map<int, int> dict;
            for (auto n : nums) dict[n]++;
            
            // max heap of pair<int, int>, compared by the second item
            auto cmp = [](const pii &p1, pii &p2) { return p1.second < p2.second; };
            priority_queue<pii, vector<pii>, decltype(cmp)> heap(dict.begin(), dict.end(), cmp);
            
            // constructs result vector
            vector<int> topK;
            for (int i = 0; i < k; i++) {
                topK.push_back(heap.top().first);
                heap.pop();
            }
            
            return topK;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.