Share my C++ solution using bucket sort,easy to understand


  • 0
    V
    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            vector<int> ret;
            vector<vector<int>> bucket((unsigned int)nums.size() + 1);
            unordered_map<int, int> my_hash;
            unsigned int i = 0;
            unsigned int j = 0;
            unsigned int n = nums.size();
            
            for (i = 0; i < n; i++)
            {
                my_hash[nums[i]]++;
            }
            
            unordered_map<int, int>::iterator it = my_hash.begin();
            for (; it != my_hash.end(); it++)
            {
                bucket[it->second].push_back(it->first);
            }
            
            for (i = bucket.size()-1; i > 0; i--)
            {
                for (j = 0; j < bucket[i].size(); j++)
                {
                    ret.push_back(bucket[i][j]);
                    if (ret.size() == k)
                        return ret;
                }
            }
            
            return ret;
        }
    };

Log in to reply
 

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