164. 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.
1 public class Solution { 2 public int maximumGap(int[] nums) { 3 // corner case:if the input is null or the length of the input array is zero or one 4 if(nums==null||nums.length<2) return 0; 5 int min = Integer.MAX_VALUE; 6 int max = Integer.MIN_VALUE; 7 //find the min and max of the array 8 for(int i=0;i<nums.length;i++){ 9 min = Math.min(min,nums[i]); 10 max = Math.max(max,nums[i]); 11 } 12 // Math.ceil is the min Integer that >= i;Math.floor is the max integer that <=i; 13 // the gap represents the average gap value between two numbers 14 int gap = (int)Math.ceil((double)(max-min)/(nums.length-1)); 15 int[] bucketsMax = new int[nums.length-1]; 16 int[] bucketsMin = new int[nums.length-1]; 17 Arrays.fill(bucketsMax,Integer.MIN_VALUE); 18 Arrays.fill(bucketsMin,Integer.MAX_VALUE); 19 // put numbers into buckets 20 for(int i:nums){ 21 if(i==min||i==max) continue; 22 int idx = (i-min)/gap; 23 bucketsMax[idx] = Math.max(i,bucketsMax[idx]); 24 bucketsMin[idx] = Math.min(i,bucketsMin[idx]); 25 } 26 int maxGap = Integer.MIN_VALUE; 27 int previous = min; 28 // find the max neighboring buckets 29 for(int i=0;i<nums.length-1;i++){ 30 if(bucketsMin[i]==Integer.MAX_VALUE||bucketsMax[i] ==Integer.MIN_VALUE){ 31 continue; 32 } 33 maxGap = Math.max(maxGap,bucketsMin[i]-previous); 34 previous = bucketsMax[i]; 35 } 36 maxGap = Math.max(maxGap,max - previous); 37 return maxGap; 38 } 39 } 40 // the total run time could be O(n) time,and the space complexity could be O(n)