给定一个整形数组arr,返回排序后的相邻两数的最大差值。数组
时间复杂度为O(N)。spa
若是用排序法实现,其时间复杂度为O(NlogN),而若是利用桶排序的思想(不是桶排序),能够作到O(N),额外空间复杂度为O(N)。遍历arr找到最大值max和最小值min。若是arr的长度为N,准备N+1个桶,把max单独放在第N+1个桶中,[min,max)范围上的数放在1~N号桶里,对于1~N号桶中的每个桶来讲,负责的区间为(max-min)/N。若是一个数为num,它应该分配进(num-min)*len/(max-min)。排序
arr一共有N个数,旻、必定会放进1号桶中,max必定会放进最后的桶中,因此,若是把全部的数放进N+1个桶中,必然有桶是空的。产生最大差值的相邻数来自不一样桶。因此只要计算桶之间数的间距能够,也就是只用记录每一个桶的最大值和最小值,最大差值只可能来自某个非空桶的最小值减去前一个非空桶的最大值。ast
public static int maxGap(int[] nums) {if (nums == null || nums.length < 2) {return 0;
}int len = nums.length;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {min = Math.min(min, nums[i]);max = Math.max(max, nums[i]);}if (min == max) {
return 0;
}boolean[] hasNum = new boolean[len + 1];int[] maxs = new int[len + 1];int[] mins = new int[len + 1];int bid = 0;
for (int i = 0; i < len; i++) {bid = bucket(nums[i], len, min, max); // 算出桶号
mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[i]) : nums[i];maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[i]) : nums[i];hasNum[bid] = true;
}int res = 0;
int lastMax = 0;
int i = 0;
while (i <= len) {
if (hasNum[i++]) { //找到第一个不为空的桶lastMax = maxs[i - 1];break;
}}for (; i <= len; i++) {
if (hasNum[i]) {
res = Math.max(res, mins[i] - lastMax);lastMax = maxs[i];}}return res;
}//使用long类型是为了防止相乘时溢出
public static int bucket(long num, long len, long min, long max) {return (int) ((num - min) * len / (max - min));}