题目:
给定一个数组,求如果排序之后,相邻两数的最大差值,要求时间复杂度为O(N),且要求不能用非基于比较的排序
public static int maxGap(int nums[]) { if (nums == null || nums.length < 2) { return 0; } int len = nums.length; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (int i = 0; i < len; i++) { max = Math.max(max, nums[i]); min = Math.min(min, nums[i]); } if (max == min) { return 0; } 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 < len; i++) { index = bucket(nums[i], len, max, min); maxs[index] = hasNum[index] ? Math.max(nums[i], maxs[index]) : nums[i]; mins[index] = hasNum[index] ? Math.min(nums[i], mins[index]) : nums[i]; hasNum[index] = true; } int res = Integer.MIN_VALUE; int lastMax = maxs[0]; for (int i = 1; i < maxs.length; i++) { if (hasNum[i]) { res = Math.max(res, mins[i] - lastMax); lastMax = maxs[i]; } } return res; } public static int bucket(int num, int len, int max, int min) {
//这里是一个大坑,不能写成((num - min)/ (max - min))*len
return (int) ((num - min) * len / (max - min)); }