《程序员代码面试指南》第八章 数组和矩阵问题 数组排序之后相邻数的最大差值

题目

数组排序之后相邻数的最大差值

java代码

package com.lizhouwei.chapter8;

/**
 * @Description: 数组排序之后相邻数的最大差值
 * @Author: lizhouwei
 * @CreateDate: 2018/5/9 21:56
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_26 {
    public int maxGap(int[] arr) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        int len = arr.length;
        int maxGap = 0;
        for (int i = 0; i < arr.length; i++) {
            max = Math.max(max, arr[i]);
            min = Math.min(min, arr[i]);
        }
        boolean[] hasNum = new boolean[len + 1];
        int[] maxs = new int[len + 1];
        int[] mins = new int[len + 1];
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            index = bucket(arr[i], max, min, len);
            maxs[index] = hasNum[index] ? Math.max(maxs[index], arr[i]) : arr[i];
            mins[index] = hasNum[index] ? Math.min(mins[index], arr[i]) : arr[i];
            hasNum[index] = true;
        }
        int i = 0;
        while (i <= len) {
            if (hasNum[i++]) {
                max = maxs[i - 1];
                break;
            }
        }
        while (i <= len) {
            if (hasNum[i]) {
                maxGap = Math.max(maxGap, mins[i] - max);
                max = maxs[i];
            }
            i++;
        }
        return maxGap;
    }

    public int bucket(long cur, long max, long min, long len) {
        return (int) ((cur - min) * len / (max - min));
    }

    //测试
    public static void main(String[] args) {
        Chapter8_26 chapter = new Chapter8_26();
        int[] arr = {9, 3, 1, 10};
        int res = chapter.maxGap(arr);
        System.out.print("数组{9, 3, 1, 10}排序之后相邻数的最大差值: " + res);
    }
}

结果

posted @ 2018-05-09 22:25  lizhouwei  阅读(351)  评论(0编辑  收藏  举报