**LeetCode-Maximum Gap

bucket sort 

n个数的话 用n个bucket 这样可能每个bucket正好一个数字 或者有的bucket是空着的 这样的话就可以不管bucket内部的gap了 

1.假如有至少一个是空的 那在这个空的两边的bucket之间一定会形成max gap 

2.假如每个正好一个数字 那么每个数字间的gap实际就是每个bucket之间的gap


bucket size 就是(max - min ) / n 取ceiling

需要记录每个bucket的min max

然后计算bucket之间的gap就行了

public class Solution {
    public int maximumGap(int[] nums) {
        if ( nums == null )
            return 0;
        int n = nums.length;
        if ( n < 2 )
            return 0;
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for ( int i = 0; i < n; i ++ ){
            min = Math.min ( min, nums[ i ] );
            max = Math.max ( max, nums[ i ] );
        }
        double k =(double)( max - min ) / ( double )n;
        System.out.println(k);
        if ( k == 0 )
            return 0;
        int [] mins = new int [n];
        int [] maxs = new int [n];
        Arrays.fill ( mins, Integer.MAX_VALUE );
        Arrays.fill ( maxs, Integer.MIN_VALUE );
        for ( int i = 0; i < n; i ++ ){
            int index = (int)(( nums [ i ] - min ) / k);
            System.out.println(index);
            if ( index == n )
                index --;
            mins [ index ] = Math.min ( mins[ index ], nums [ i ] );
            maxs [ index ] = Math.max ( maxs[ index ], nums [ i ] );
        }
        int gap = 0, prev = maxs[0];
        for ( int i = 1; i < n; i ++ ){
            if ( mins[ i ] != Integer.MAX_VALUE ){
                gap = Math.max ( gap, mins[ i ] - prev );
                prev = maxs [ i ];
            }
        }
        return gap;
    }
}


你可能感兴趣的:(**LeetCode-Maximum Gap)