From : https://leetcode.com/problems/maximum-gap/
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.
思路 :用桶排序原理,将n个数放入n个桶中,记录每个桶中的最大和最小值。
如果n个数分别在n个桶中,那么后一桶的最大(同时也是最小)与前一桶的最小(同时也是最大)之差的最大就是maxGap; 否则,如果n个数不全在n个桶中,那么必然有空桶,空桶后一个的最小和前一个的最大的差必然比桶的长度达,那么后桶最小和前桶最大之差的最大仍然是maxGap。
综上所述,取 max{buckets[0].max-buckets[0].min, buckets[n-1].max-buckets[n-1].min, max {buckets[i].min-buckets.max}} , 即buckets[0].max-buckets[0].min , buckets[n-1].max-buckets[n-1].min 和 max {buckets[i].min-buckets.max}的最大值。
public class Solution {
class Bucket {
// if min < 1, the bucket is empty
int min = -1;
int max;
}
public int maximumGap(int[] nums) {
if(nums.length < 2) {
return 0;
}
int len = nums.length;
int gmax = nums[0], gmin = gmax;
for(int i=1; i<len; ++i) {
int c = nums[i];
if(c < gmin) {
gmin = c;
} else if(c > gmax) {
gmax = c;
}
}
int size = (int) Math.ceil( (double)(gmax - gmin + 1) / (double)len );
Bucket[] buckets = new Bucket[len]; // len buckets
for(int i=0; i<len; ++i) {
buckets[i] = new Bucket();
}
for(int num : nums) {
Bucket bucket = buckets[(num-gmin)/size];
if(bucket.min < 0) {
// empty bucket
bucket.min = bucket.max = num;
} else {
if(num < bucket.min) {
bucket.min = num;
} else if(num > bucket.max) {
bucket.max = num;
}
}
}
int min = buckets[0].min, max=min, maxGap = buckets[0].max-min;
for(Bucket b : buckets) {
if(b.min < 0) {
continue;
}
min = b.min;
if(min - max > maxGap) {
maxGap = min-max;
}
max = b.max;
}
return gmax-min > maxGap ? gmax-min : maxGap;
}
}