1. 程式人生 > >[leetcode]Maximum Gap

[leetcode]Maximum Gap

題目描述如下:

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.

截圖思路:本題目中主要是給定一個未排序的陣列,得到排序後的陣列中相鄰的兩個元素的最大差值,並且要求是線上性時間內。因此,如果先對陣列進行排序再求得最大差值的話,時間複雜度就會很高。其中,線性的排序演算法主要有:計數排序,基數排序和桶排序。

桶排序的思想是:把陣列區間內換分為n個相同大小的子區間,或稱桶,然後,將n個輸入分不到各個桶中去。因為輸入數均勻分佈在區間上,所以一般不會有很多數落在一個桶中的情況。為得到結果,先對各個桶中的數進行拍戲,然後按照次序把桶中的元素列出來即可。因此,我們為了得到最大差值,只需要計算一個桶裡面的相鄰兩個數之間的最大差值,或者是兩個相鄰桶的最大值與最小值之間的差值,取其中的最大者最為最終最大差值。

可以先得到陣列中的最大值與最小值之間的差值,然後根據最大值與最小值的差值,以及陣列的大小,得到Gap,以及桶的個數。接下來將陣列中的元素放入桶中,最後計算各個桶內以及桶間差值的最大值,得到最終結果。

程式碼實現如下:

public int maximumGap(int[] nums) {
         int m=nums.length;
        if(m<2)return 0;
        //找到最大值和最小值,為了計算桶的大小
        int max=nums[0];
        int min=nums[0];
        for(int i=0;i<m;i++){
            if(max<nums[i])max=nums[i];
            if(min>nums[i])min=nums[i];
        }
        int agGap=(int)Math.ceil((max-min)/(double)m);//表示桶的大小
        int bucketsSize=(int)Math.ceil((max-min)/(double)agGap);
        //總共有m-1個,並且對其初始化
        List<Integer>[] buckets=new List[bucketsSize];
        for(int  i=0;i<buckets.length;i++){
            buckets[i]=new LinkedList<Integer>();
        }
        //將其中的所有放到桶裡面
        for(int i=0;i<m;i++){
            int bucketIndex=(nums[i]-min)/agGap;
            if(bucketIndex==bucketsSize) bucketIndex--;
            buckets[bucketIndex].add(nums[i]);
        }
        int maxGap=Integer.MIN_VALUE;
        int previousmax=min;
        for(int i=0;i<bucketsSize;i++){
            if(buckets[i].isEmpty()) continue;
            int bucketmin=Collections.min(buckets[i]);
            int bucketmax=Collections.max(buckets[i]);
            maxGap=Math.max(maxGap,bucketmax-bucketmin);
            maxGap=Math.max(maxGap,bucketmin-previousmax);
            previousmax=bucketmax;
        }

        return maxGap;
    }