c++ 32ms priority_queue and unordered_map


  • 0
    G
    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) 
        {
            unordered_map<int, int> counts;
            counts.reserve(nums.size());
    
            for(n : nums)
            {
                ++counts[n];
            }
            
            typedef pair<int, int> IntPair;
            priority_queue<IntPair, vector<IntPair>, std::less<IntPair>> topK;
            for(c : counts)
            {
                topK.push(IntPair(c.second, c.first));
            }
    
            vector<int> result;
            result.reserve(k);
            for(int i = 0; i < k; ++i)
            {
                result.push_back(topK.top().second);
                topK.pop();
            }        
            return result;
        }
    };
    

Log in to reply
 

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