C++_Radix Sort_Time: O(k*n), Space: O(k*n)


  • 0

    k is the number of digits of the largest number in the vector, k <= 32.

    class Solution {
    public:
    int maximumGap(vector<int>& nums) {
        if(nums.size() < 2) return 0;
        int Max = nums[0];
        for(auto num : nums){Max = max(Max, num);}
        int k = 0;
        while(Max >> k && k <= 32){k++;}
        
        vector<queue<int>> bucket(10);
        for(int digit = 0; digit <= k; ++digit){
            for(int i = 0; i < nums.size(); ++i){
                int dth = (nums[i]>>(digit-1)) % 10;
                bucket[dth].push(nums[i]);
            }
            int index = 0;
            for(int i = 0; i < 10; i++){
                while(!bucket[i].empty()){
                    nums[index++] = bucket[i].front();
                    bucket[i].pop();
                }
            }
        }
        int Gap = 0;
        for(int i = 1; i < nums.size(); ++i){
            Gap = max(nums[i]-nums[i-1], Gap);
        }
        return Gap;
    }
    };

Log in to reply
 

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