URL
https://leetcode.com/problems/maximum-gap/description/
描述
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.
解题思路
基本思路是桶排序。
步骤如下:
1. 遍历整个数组,求出最小值min,最大值max.
2. 求出平均每两个相邻的数字之间的平均差,(max-min)/(n-1)
这里解释一下,我们可以想象n个数字会有n-1个间隔,上面的公式会求出平均间隔的大小。
3. 接下来遍历数组把每一个数字放到相应的间隔中(这里的间隔就是桶,num[i] = min+ gap*k, 则把num[i]放入第K个桶中)。放入桶的时候我们只记录这个桶中的最小值和最大值。
4. 之后遍历所有桶, 在前一个桶的最大值和后一个桶的最小值的差值中找最大的差值。
代码示例
public int maximumGap(int[] nums) {
if(nums==null) return 0;
int len = nums.length;
if(len ==0 || len == 1)
return 0;
if(len==2){
return Math.abs(nums[0]-nums[1]);
}
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int num:nums){
min = Math.min(num,min);
max = Math.max(num,max);
}
if(min==max) return 0;
int everageGap = (max-min)/ (len-1) +1;
int[] bucketMin = new int[len];
int[] bucketMax = new int[len];
Arrays.fill(bucketMin,Integer.MAX_VALUE);
Arrays.fill(bucketMax,Integer.MIN_VALUE);
int idx = 0;
for(int num: nums){
idx = (num - min)/everageGap;
bucketMin[idx] = Math.min(num,bucketMin[idx]);
bucketMax[idx] = Math.max(num,bucketMax[idx]);
}
int res = Integer.MIN_VALUE;
int lastMax = -1;
for(int i=0;i<len;i++){
if(bucketMin[i]==Integer.MAX_VALUE){
continue;
}
if(lastMax != -1){
res = Math.max(res,bucketMin[i] - lastMax);
}
lastMax = bucketMax[i];
}
return res;
}