Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Discuss里面有个解释是:
Suppose there are N elements in the array, the min value is min and the max value is max. Then the maximum gap will be no smaller than ceiling[(max - min ) / (N - 1)].
Let gap = ceiling[(max - min ) / (N - 1)]. We divide all numbers in the array into n-1 buckets, where k-th bucket contains all numbers in [min + (k-1)gap, min + k*gap). Since there are n-2 numbers that are not equal min or max and there are n-1 buckets, at least one of the buckets are empty. We only need to store the largest number and the smallest number in each bucket.
After we put all the numbers into the buckets. We can scan the buckets sequentially and get the max gap.
O(n)时间复杂度,所以用桶排序
O(n)空间复杂度,要考虑优化:分多个桶,把一个区间的数放到一个桶里面,怎么放呢?应该是放一些关键的,最大值?最小值?
因为gap最小是 (int) Math.ceil((double)(max-min)/(len-1)) ,就把原始数据切分到 len-1 段,每一段的长度是gap, 分别求出每一段的最大最小值保存到数组中,最后求出求前一个max和下一个min最大的差值。
import java.util.Arrays;
/*
* O(n)时间复杂度,所以用桶排序
* O(n)空间复杂度,要考虑优化:分多个桶
*/
public class Solution {
public int maximumGap(int[] nums) {
if(nums == null || nums.length < 2) return 0;
if(nums.length == 2) return Math.abs(nums[0] - nums[1]);
int len = nums.length;
// 先求出最大最小
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for(int n : nums) {
if(n < min) min = n;
if(n > max) max = n;
}
if(max == min) return 0;
// 分桶
// 桶间距,也是最小的gap,求出来的gap肯定不会小于它,所以可以利用minGap来分组
int minGap = (int) Math.ceil((double)(max-min)/(len-1));
int[] groupMax = new int[len-1]; // 最多需要长度为len-1
int[] groupMin = new int[len-1];
Arrays.fill(groupMax, Integer.MIN_VALUE);
Arrays.fill(groupMin, Integer.MAX_VALUE);
for(int n : nums) {
int mapIdx = (n - min) / (1 + minGap);
groupMin[mapIdx] = Math.min(n, groupMin[mapIdx]);
groupMax[mapIdx] = Math.max(n, groupMax[mapIdx]);
}
// 求前一个max和下一个min最大的差值
int rst = Integer.MIN_VALUE;
for(int i=1; i<len-1; i++) {
int start = groupMax[i-1], end = groupMin[i];
// 缺少该数,一直往前查找直到有一个存在的值
if(start == Integer.MIN_VALUE) {
int tmp = i - 1;
// 先找到一个有数据的Group
while(groupMax[tmp] == Integer.MIN_VALUE && groupMin[tmp] == Integer.MAX_VALUE) tmp --;
// 优先判断groupMax[tmp]是不是存在的
if(groupMax[tmp] != Integer.MIN_VALUE) start = groupMax[tmp];
else start = groupMin[tmp];
}
if(end == Integer.MAX_VALUE) {
int tmp = i;
while(groupMax[tmp] == Integer.MIN_VALUE && groupMin[tmp] == Integer.MAX_VALUE) tmp --;
if(groupMin[tmp] != Integer.MAX_VALUE) end = groupMin[tmp];
else end = groupMax[tmp];
}
if(end - start > rst)
rst = end - start;
}
return rst;
}
}