**Leetcode 164. Maximum Gap | 桶排序

https://leetcode.com/problems/maximum-gap/description/

思路:

(max-min)/(nums.size()-1) 这个是ans的下限,所以就把各个数字放进桶里,桶的大小就是这个下限。在一个桶里的数字的gap绝对不可能是ans(因为小于下限),只有相邻桶才可能是答案


class Solution {
public:
    int maximumGap(vector& nums) {
        if (nums.size() <= 1) return 0;
        int mmin = nums[0], mmax = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            mmin = min( mmin, nums[i] );
            mmax = max( mmax, nums[i] );
        }
        int bucket_size = (mmax - mmin)/(nums.size() - 1);
        
        if (bucket_size == 0) {
            if (mmax == mmin) return 0;
            bucket_size = 1;
        }
        
        int bucket_cnt = (mmax-mmin) / bucket_size;
        vector bucket_min( bucket_cnt + 1, INT_MAX );
        vector bucket_max( bucket_cnt + 1, INT_MIN );
        vector b_cnt( bucket_cnt + 1, 0 );
        
        for (int i = 0; i < nums.size(); i++) {
            
            int bucket_id = (nums[i] - mmin) / bucket_size;
            b_cnt[bucket_id] ++;
            bucket_min[bucket_id] = min(bucket_min[bucket_id], nums[i]);
            bucket_max[bucket_id] = max(bucket_max[bucket_id], nums[i]);
        }
        
        int ans = INT_MIN, last_max = bucket_max[0];
        for (int i = 1; i < bucket_min.size(); i++) {
            if (!b_cnt[i]) continue;
            
            ans = max(bucket_min[i] - last_max, ans);
            last_max = bucket_max[i];
        }
        
        return ans;
    }
};


你可能感兴趣的:(LeetCode题解)