天题系列: Maximum Gap --bucket sort

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

OG soln:

Suppose there are N elements and they range from A to B.

Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]

Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket

for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.

Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.

For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.

 

"in its sorted form." 这里就暗示了必须得排序,所以之后找结果就是两个相邻桶之间的计算。最后计算的时候,是n-1个桶的最大值,和n个桶的最小值之间的差,同样,是因为要sorted form

public class Solution {

    public int maximumGap(int[] num) {

        // bucket sort

        if(num==null || num.length<2) return 0; //bug

        

        int min = num[0], max = min;

        for(int i=0; i< num.length ; i++){

            if (min> num[i]) min = num[i];

            if(max< num[i]) max = num[i];

        }

        int len = (max-min)/(num.length-1); //bucket length, bucket has unlimit capacity

        if (len == 0 ) return max-min;

        int n = (max-min) / len +1; // buckets' number

        int[] bucketMin = new int[n];

        int[] bucketMax = new int[n];

        

        for(int i=0; i<n; i++){     // padding the buckets

            bucketMin[i]=Integer.MAX_VALUE;

            bucketMax[i]=Integer.MIN_VALUE;

        }

        

        for(int i=0; i< num.length; i++){

            int ind = (num[i]-min)/len;

            bucketMin[ind] = Math.min(bucketMin[ind], num[i]); // fill in buckets

            bucketMax[ind] = Math.max(bucketMax[ind], num[i]);

        }

        

        bucketMin[0] = min;

        bucketMax[n-1] = max;

        

        // 考虑怎么找到相邻的gapMax 问题: gap 必然出现在相邻桶的最大,最小之间

        int res = Integer.MIN_VALUE;

        int tmp = min;

        for(int ind=0; ind < n; ind++){

            if(bucketMin[ind]==Integer.MAX_VALUE || bucketMax[ind]==Integer.MIN_VALUE ) continue;

            res = Math.max(res, bucketMin[ind]-tmp);

            tmp = bucketMax[ind];

        }



        return res;

    }

}

 

你可能感兴趣的:(sort)