C++ hashmap and vector solution.


  • 0
    P
    1. Count all numbers.
    2. Insert into a vector<vector<int>>v where v[i] = all numbers with freq i.
    3. reverse v.
    4. till the number of elements found is less than k, push all elements of v[i] to solution.
    5. resize solution to size k, discarding some elements if necessary.
      return
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
             vector<vector<int>>freqmap(nums.size() + 1, vector<int>(0));
             unordered_map<int , int> numcount;
             vector<int>soln;
             for(auto &x : nums)numcount[x]++;
             for(auto &x : numcount)
             {
                 freqmap[x.second].push_back(x.first);
             }
             reverse(freqmap.begin(), freqmap.end());
             for(auto &v : freqmap)
             {
                 if(v.size())
                 {
                     for(auto &x : v)
                     {
                         soln.push_back(x);
                     }
                 }
                 if(soln.size() >= k)break;
             }
             soln.resize(k);
             return soln;
        }
    };```

Log in to reply
 

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