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.
O(n)的时间复杂度排序有桶排序 基数排序和计数排序。这里采用的是桶排序思想。求排序之后相邻元素的最大差值,这种情况只有可能出现在桶与桶之间,也就是说桶与桶之间的距离肯定大于桶内元素的距离。当然,如果元素全部都一样,那只能是桶内的元素了。
public int maximumGap(int[] num) {
if(num.length<2) return 0;
int max=Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i=0;i<num.length;i++) {
if(num[i]>max) max = num[i];
if(num[i]<min) min = num[i];
}
if(min==max) return 0; //数字相同,则在一个桶内
//桶容量
int size = (max-min)/num.length + 1; //至少一个桶 不为0
//桶个数
int nums = (max-min)/size + 1;//最大的数放在最后一个桶中
//记录每个桶的最小值/最大值
int[] bMin = new int[nums];
int[] bMax = new int[nums];
//填充数组
Arrays.fill(bMin, Integer.MAX_VALUE);
Arrays.fill(bMax, Integer.MIN_VALUE);
for(int i=0;i<num.length;i++) {
//放入几号桶
int tmp = (num[i]-min)/size;
bMin[tmp] = Math.min(num[i], bMin[tmp]);
bMax[tmp] = Math.max(num[i], bMax[tmp]);
}
//要求的最大距离
int res = Integer.MIN_VALUE;
int pre = bMax[0]; //上一个桶的最大值
for(int i=1;i<nums;i++) {
if(bMin[i]==Integer.MAX_VALUE && bMax[i]==Integer.MIN_VALUE) {
continue; //空桶丢弃
}
res=Math.max(res, bMin[i]-pre); //当前桶的最小值
pre=bMax[i];
}
return res;
}