My 36ms C++ solution using partial_sort


  • 0
    I
      struct Compare 
      {
          bool operator()(const pair<int,int> &l, const pair<int,int> &r) { return l.second > r.second;}
      };
    
      vector<int> topKFrequent(vector<int>& nums, int k) 
      {
            vector<int> ans;
            int n = nums.size();
            if(!n)
               return ans;
            unordered_map<int,int> m;
            for(int i = 0; i < n; ++i)
                 ++m[nums[i]];
            vector<pair<int,int>> vec(m.begin(), m.end());
            k = min(k,int(vec.size()));
            partial_sort(vec.begin(), vec.begin() + k, vec.end(), Compare());
            for (int i = 0; i < k; ++i)
              ans.push_back(vec[i].first);
            return ans;
      }
    

  • 0
    A
    This post is deleted!

Log in to reply
 

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