int bucket_size = Math.max(1,(Max-Min)/(N) + 1);//ceil( (Max-Min)/(N-1) ) = (Max-Min-1)/(N-1) + 1or int bucket_size = (int)Math.ceil( ((double)(Max-Min))/(N-1) );int bucket_count = (Max-Min)/bucket_size + 1;
下面用桶排序实现,这也是leetcode上给出的参考解法:
Suppose there are N elements and they range from A to B.
Then the maximum gap will be no smaller than ceiling[(B - A) / (N - 1)]
Let the length of a bucket to be len = ceiling[(B - A) / (N - 1)], then we will have at most num = (B - A) / len + 1 of bucket
for any number K in the array, we can easily find out which bucket it belongs by calculating loc = (K - A) / len and therefore maintain the maximum and minimum elements in each bucket.
Since the maximum difference between elements in the same buckets will be at most len - 1, so the final answer will not be taken from two elements in the same buckets.
For each non-empty buckets p, find the next non-empty buckets q, then q.min - p.max could be the potential answer to the question. Return the maximum of all those values.
//latest version
//刷题确实是有用的,至少到现在,对于java data structure 已经很熟练了
public int maximumGap(int[] nums) {
if(nums.length < 2)
return 0;
int min = nums[0], max = nums[0];
for(int n : nums){
min = Math.min(min, n);
max = Math.max(max, n);
}
if(min == max)
return 0;
int len = nums.length;
//doesn't matter how much exactly, just make sure smaller than (int)Math.ceil((double)(max-min)/(len-1))
//here use ceil because return value is int
int bucketSize = (int)Math.ceil((double)(max-min)/(len-1));// or bucketSize -= 10;
ArrayList all = new ArrayList();
//doesn't matter how many exactly, just make sure larger than (max-min)/bucketSize
int bucket_count = (max-min)/bucketSize + 1000000;
for(int i=0; i> buckets = new ArrayList>();
for(int i=0; i<= bucket_count; i++){
List temp = new ArrayList();
buckets.add(temp);
}
for(int i=0; i bucket = buckets.get(ind);
bucket.set(0, Math.min(bucket.get(0),nums[i]));
bucket.set(1, Math.max(bucket.get(1),nums[i]));
}
}
int res = 0;
int prev = buckets.get(0).get(1);
for(int i=1; i bucket_used = new HashSet();
for(int i=0;i