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.
这里讲的很清楚:https://github.com/tg123/leetcode/tree/gh-pages/maximum-gap
中心思想就是bucket sort。把元素分别放到不同的bucket里面,每一个bucket维护最大最小值。当前bucket的最小值和上一个bucket的最大值就形成了一个gap。
不知道原创是怎么想出来的。。。
public class Solution {
private class Bucket {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
public void add(int num) {
min = Math.min(min, num);
max = Math.max(max, num);
}
}
public int maximumGap(int[] num) {
if (num.length < 2) {
return 0;
}
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < num.length; i++) {
min = Math.min(num[i], min);
max = Math.max(num[i], max);
}
int gap = (int)Math.ceil((double)(max-min)/(num.length-1));
Bucket[] buckets = new Bucket[num.length];
int maxGap = 0;
for (int i = 0; i < num.length; i++) {
int ind = (num[i]-min)/gap;
if (buckets[ind] == null) {
buckets[ind] = new Bucket();
}
buckets[ind].add(num[i]);
}
Bucket lastBucket = null;
for (int i = 0; i < num.length; i++) {
if (lastBucket != null && buckets[i] != null) {
maxGap = Math.max(maxGap, buckets[i].min-lastBucket.max);
}
if(buckets[i] != null) {
lastBucket = buckets[i];
}
}
return maxGap;
}
}