桶排序 补充问题
程序员文章站
2022-02-11 06:28:18
...
给定一个数组,求如果排序之后,相邻两数的最大差值,要求时
间复杂度O(N),且要求不能用非基于比较的排序。(面试高频题)
代码如下:
public class MaxGap {
public static int maxGap(int[] arr) {
if (arr==null && arr.length<2) {
return 0;
}
int len = arr.length;
int mix = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i=0; i<len; i++) {
mix = Math.min(mix, arr[i]);
max = Math.max(max, arr[i]);
}
if (mix == max) {
return 0;
}
boolean[] hasnum = new boolean[len+1];
int[] mixs = new int[len+1];
int[] maxs = new int[len+1];
for (int i=0; i<len; i++) {
int bid = bucket(arr[i], len, mix, max);
mixs[bid] = hasnum[i] ? Math.min(mixs[i], arr[i]):arr[i];
maxs[bid] = hasnum[i] ? Math.max(maxs[i], arr[i]):arr[i];
hasnum[bid] = true;
}
int res = 0;
int lagest = maxs[0];
int j=1;
for (; j<len+1; j++) {
if (hasnum[j]) {
res = Math.max(res, mixs[j]-lagest);
lagest = maxs[j];
}
}
System.out.println(res);
return res;
}
public static int bucket (long num, long len, long mix, long max) {
return ((int)((num - mix)*len/(max-mix)));
}
public static void main(String[] args) {
int[] arr = {2,3,5,1,9,8,4};
//maxGap(arr);
System.out.println(maxGap(arr));
}
}