给定一个数组,求如果排序之后,相邻两数的最大差值。要求时间复杂度O(N),且要求不能用非基于比较的排序。
此题用了桶排序的思想,但是没有真正排序。 假设数组中有N个数,则开一个N+1大小的数组表示有N+1个桶,确保最大差值中的两个数一定在不同的桶中。在数进桶的过程中记录每一个桶的最大值,最小值及是否进来过数。最后的最大差值为所有前一个非空桶的最大值和目前这个桶的最小值之间的差值的最大值。
import java.util.Arrays;
public class MaxGap {
public static int maxGap (int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int n : nums) {
min = Math.min(min, n);
max = Math.max(max, n);
}
if (min == max) {
return 0;
}
int len = nums.length;
boolean[] hasNum = new boolean[len+1];
int[] mins = new int[len+1];
int[] maxs = new int[len+1];
int bid = 0;
for (int n : nums) {
bid = bucket(n, len, min, max);
mins[bid] = hasNum[bid] ? Math.min(mins[bid], n) : n;
maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], n) : n;
hasNum[bid] = true;
}
int res = 0;
int lastMax = maxs[0];
int i = 1;
for (; i <= len; ++i) {
if (hasNum[i]) {
res = Math.max(res, mins[i] - lastMax);
lastMax = maxs[i];
}
}
return res;
}
public static int bucket (long num, long len, long min, long max) {
return (int) ((num-min) * len / (max-min));
}
// for test
public static int comparator(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
Arrays.sort(nums);
int gap = Integer.MIN_VALUE;
for (int i = 1; i < nums.length; i++) {
gap = Math.max(nums[i] - nums[i - 1], gap);
}
return gap;
}
// for test
public static int[] generateRandomArray(int maxSize, int maxValue) {
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
}
return arr;
}
// for test
public static int[] copyArray(int[] arr) {
if (arr == null) {
return null;
}
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
// for test
public static void main(String[] args) {
int testTime = 500000;
int maxSize = 100;
int maxValue = 100;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = copyArray(arr1);
if (maxGap(arr1) != comparator(arr2)) {
succeed = false;
break;
}
}
System.out.println(succeed ? "Nice!" : "Fucking fucked!");
}
}