import java.util.Arrays;
/**
* @Description: 求乱序数组如果排序后相邻两个数的最大差值,要求时间复杂度O(N),不能用非基于比较的排序
* @author: harold
* @date: 2021年11月10日 7:50
*/
public class MaxGap {
//数组data[N]
//设计N+1个桶bucket, 标号[0,N]
//每个bucket有一个boolean[N+1] hasNum,一个int[N+1] max,一个int[N+1] min
//从1号桶开始往后遍历,每个非空桶的min减去前一个非空桶的max,max用lastMax存
public static int maxGap(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
//找出nums里的min和max
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);
}
if (min == max) {
return 0;
}
if (max - min == 1) {
return 1;
}
//桶的个数
int lenOfBuckets = nums.length + 1;
//填充桶里面的三个值
boolean[] hasNum = new boolean[lenOfBuckets];
int[] mins = new int[lenOfBuckets];
int[] maxs = new int[lenOfBuckets];
int bid = 0;
for (int i = 0; i < nums.length; i++) {
bid = bucket(nums[i], lenOfBuckets-1, 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;
}
//遍历桶,找出当前桶min与前一个非空桶的max的差值的最大值
int maxGap = 0;
int lastMax = maxs[0];
for (int i = 1; i < lenOfBuckets; i++) {
if (hasNum[i]) {
maxGap = Math.max(maxGap, mins[i] - lastMax);
lastMax = maxs[i];
}
}
return maxGap;
}
//获取桶的标号
/**
*
* @param num 原始数组中元素值
* @param len 原始数组长度
* @param min 原始数组最小值
* @param max 原始数组最大值
* @return
*/
private static int bucket(long num, long len, long min, long max) {
return (int) ((num - min) * len / (max - min));
}
//=============for test==================
/**
* 绝对正确但复杂度高的算法
*/
private static int comparator(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
Arrays.sort(nums);
int maxGap = Integer.MIN_VALUE;
for (int i = 1; i < nums.length; i++) {
maxGap = Math.max(maxGap, nums[i] - nums[i - 1]);
}
return maxGap;
}
/**
* 随机样本产生器
*/
private static int[] generateRandomArray(int maxSize, int maxValue) {
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < arr.length; i++) {
// [-(maxValue - 1), maxValue]
arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
}
return arr;
}
public static void main(String[] args) {
int testTime = 50000;
int maxSize = 100;
int maxValue = 100;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = Arrays.copyOf(arr1, arr1.length);
if (maxGap(arr1) != comparator(arr2)) {
succeed =false;
break;
}
}
System.out.println(succeed ? "Nice!" : "Fucking fucked!");
}
}
(一)、MaxGap
最新推荐文章于 2024-08-30 18:40:43 发布