java無序數組排序後的最大相鄰差

/**
 * 無序數組排序後的最大相鄰差
 * 思路:
 * 1、利用桶排序的思想,根據原數組的長度n,創建出n個桶,每個桶代表一個區間範圍。其中第一個桶從原始數組的最小值minx開始,區間跨度是(max-min)/(n-1)
 * 2、遍歷原數組,將原始數組每個元素插入到對應桶中,記錄每個桶的最大和最小值
 * 3、遍歷所有桶,統計出每個桶的最大值,和這個桶右側非空桶的最小值的差,數值最大的差即爲原數組排序後相鄰的最大值
 *
 * 不需要像標準桶排序一樣給沒個桶內進行排序,只需要記錄桶內最大值和最小值即可,時間複雜度穩定爲O(n)
 */
public class MaxSortedDistance {

    public static int getMaxSortedDistance(int[] array){

        //1、得到數列的最大值和最小值和差值d
        int max = array[0];
        int min = array[0];
        for(int i=1;i<array.length;i++){
            if(array[i] > max){
                max = array[i];
            }
            if(array[i] < min){
                min = array[i];
            }
        }
        int d = max - min;
        //如果max和min相等,說明數組中所有的值都相等
        if(d == 0){
            return 0;
        }

        //2、初始化桶
        int bucketLength = array.length;
        Bucket[] buckets = new Bucket[bucketLength];
        for(int i =0;i<bucketLength;i++){
            buckets[i] = new Bucket();
        }

        //3、遍歷原始數組,求出每個桶的最大值和最小值
        for (int i=0;i<bucketLength;i++){
            int index = (array[i] - min) * (bucketLength - 1)/d;
            if(buckets[index].min == null || buckets[index].min > array[i]){
                buckets[index].min = array[i];
            }
            if(buckets[index].max == null || buckets[index].max < array[i]){
                buckets[index].max = array[i];
            }
        }
        //4、遍歷桶,找到最大差
        int leftMax = buckets[0].max;
        int maxDistance = 0;
        for(int i=1;i<bucketLength;i++){
            if(buckets[i].min == null){
                continue;
            }
            if(buckets[i].min - leftMax > maxDistance){
                maxDistance = buckets[i].min - leftMax;
            }
            leftMax = buckets[i].max;
        }
        return maxDistance;

    }

    private static class Bucket{
        private Integer min;
        private Integer max;
    }

    public static void main(String[] args) {
        int[] array = new int[]{2,6,3,4,5,10,9};
        System.out.println(getMaxSortedDistance(array));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章