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.
Solution 1:O(n*logn)
public class Solution {
public int maximumGap(int[] nums) {
int len=nums.length;
if(len<2)
return 0;
int gap=0;
Arrays.sort(nums);
for(int i=0;i<len-1;++i){
int temp=nums[i]-nums[i+1]>0?nums[i]-nums[i+1]:nums[i+1]-nums[i];
if(temp>gap)
gap=temp;
}
return gap;
}
}
Solution 2:O(n) Find in discuss:Use bucket sort:
public class Solution {
public int maximumGap(int[] nums) {
int n=nums.length;
if(n<2)
return 0;
int max=nums[0];
int min=nums[0];
for(int i:nums){
max=Math.max(max,i);
min=Math.min(min,i);
}
int gap=(int)Math.ceil((double)(max-min)/(n-1));
int[] bucketmaxs=new int[n-1];
int[] bucketmins=new int[n-1];
Arrays.fill(bucketmaxs,Integer.MIN_VALUE);
Arrays.fill(bucketmins,Integer.MAX_VALUE);
for(int i:nums){
if(i==min||i==max)
continue;
int index=(i-min)/gap;
bucketmaxs[index]=Math.max(i,bucketmaxs[index]);
bucketmins[index]=Math.min(i,bucketmins[index]);
}
int pre=min;
int maxgap=Integer.MIN_VALUE;
for(int i=0;i<n-1;++i){
if(bucketmins[i]==Integer.MAX_VALUE&&bucketmaxs[i]==Integer.MIN_VALUE)
continue;
maxgap=Math.max(maxgap,bucketmins[i]-pre);
pre=bucketmaxs[i];
}
maxgap=Math.max(maxgap,max-pre);
return maxgap;
}
}