You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.3 KiB
52 lines
1.3 KiB
package class07;
|
|
|
|
// 测试链接 : https://leetcode.com/problems/maximum-gap/
|
|
public class Code03_MaxGap {
|
|
|
|
public static int maximumGap(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 = 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(int num, int len, int min, int max) {
|
|
// 一个桶的范围
|
|
double range = (double) (max - min) / (double) len;
|
|
// num和min之间的距离
|
|
double distance = (double) (num - min);
|
|
// 返回桶的编号,向下取整
|
|
return (int) (distance / range);
|
|
}
|
|
|
|
}
|