Solution 1
class Solution {
public int maximumGap(int[] nums) {
if(nums == null || nums.length < 2){
return 0;
}
int m = Integer.MIN_VALUE;
for(int num:nums){
m = Math.max(m, num);
}
int exp=1;
int R = 10;
int[] aux = new int[nums.length];
while(m/exp>0){
int[] count = new int[R];
for(int i=0;i<nums.length;i++){
count[(nums[i]/exp)%10]++;
}
//得到以0-9结尾数所在的相对位置
for(int i=1;i<count.length;i++){
count[i] += count[i-1];
}
//由于aux是0开始的index,但是count里是个数,所以-1
for(int i=nums.length-1;i>=0;i--){
aux[--count[(nums[i]/exp)%10]] = nums[i];
}
for(int i=0;i<nums.length;i++){
nums[i] = aux[i];
}
exp*=10;
}
int max = 0;
for(int i=1;i < nums.length;i++){
max = Math.max(max, nums[i]-nums[i-1]);
}
return max;
}
}
Solution 2 :bucket sort
核心:average gap is (max - min)/(n - 1)
so if we set the extent of a bucket is < average, then max gap must be inter-bucket gap, or else it disobey the definition of average.
the special case is gap is exactly equal to average gap. then the max gap equals to max gap.
so the gap of each bucket is (int)Math.ceil((double)(max - min)/(n - 1));
class Solution {
public int maximumGap(int[] nums) {
if(nums == null||nums.length < 2){
return 0;
}
int min = nums[0];
int max = nums[0];
for(int i=0;i<nums.length;i++){
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);
}
int n = nums.length;
int k = n-1;
int gap = (int)Math.ceil((double)(max - min)/(n - 1));
int[] bucketsMIN = new int[n - 1]; // store the min value in that bucket
int[] bucketsMAX = new int[n - 1]; // store the max value in that bucket
Arrays.fill(bucketsMIN, Integer.MAX_VALUE);
Arrays.fill(bucketsMAX, Integer.MIN_VALUE);
for(int num:nums){
if(num==min||num==max) continue;
int idx = (num-min)/gap;
bucketsMIN[idx] = Math.min(num, bucketsMIN[idx]);
bucketsMAX[idx] = Math.max(num, bucketsMAX[idx]);
}
int maxGap = 0;
int previous = min;
for(int i=0;i<n-1;i++){
if (bucketsMIN[i] == Integer.MAX_VALUE && bucketsMAX[i] == Integer.MIN_VALUE)
// empty bucket
continue;
// min value minus the previous value is the current gap
maxGap = Math.max(maxGap, bucketsMIN[i] - previous);
// update previous bucket value
previous = bucketsMAX[i];
}
maxGap = Math.max(maxGap,max-previous);
return maxGap;
}
}