标签:
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(nlogn) Solution by Sort: 340ms
1 public int maximumGap(int[] nums) { 2 Arrays.sort(nums); 3 int len = nums.length; 4 if(len < 2) return 0; 5 int maxGap = 0; 6 for(int i=0;i<len-1;i++){ 7 int gap = nums[i+1]-nums[i]; 8 maxGap = gap>maxGap?gap:maxGap; 9 } 10 return maxGap; 11 }
O(n) Solution by Bucket: 396ms
1 public int maximumGap(int[] nums) { 2 int len = nums.length; 3 if(len < 2) return 0; 4 int max = 0, min = Integer.MAX_VALUE; 5 for(int num : nums){ 6 max = num>max?num:max; 7 min = num<min?num:min; 8 } 9 if(max == min) return 0; 10 11 int jump = (int)Math.ceil(((double)(max-min))/((double)(len-1))); 12 int size = (max - min)/jump + 1; 13 int[][] bucket = new int[size][2]; 14 for(int i=0;i<size;i++){ 15 bucket[i][0]=-1; 16 bucket[i][1]=-1; 17 } 18 for(int num:nums){ 19 int buc = (num-min)/jump; 20 if(bucket[buc][0]==-1){ 21 bucket[buc][0]=num; 22 bucket[buc][1]=num; 23 }else{ 24 int tmpMin = bucket[buc][0]; 25 int tmpMax = bucket[buc][1]; 26 bucket[buc][0] = num<tmpMin?num:tmpMin; 27 bucket[buc][1] = num>tmpMax?num:tmpMax; 28 } 29 } 30 31 int index = 0; 32 int maxGap = 0; 33 int lastMax = -1; 34 while(index<size){ 35 while(index<size && bucket[index][0]==-1){ 36 index++; 37 } 38 if(index>=size) break; 39 if(lastMax==-1){ 40 lastMax=bucket[index][1]; 41 }else{ 42 int gap = bucket[index][0] - lastMax; 43 maxGap = gap>maxGap?gap:maxGap; 44 lastMax = bucket[index][1]; 45 } 46 index++; 47 } 48 return maxGap; 49 }
由于最大间隔不会小于(max-min)/(len-1),所以以此间隔为一个桶,将unsorted的数组存入桶中,比较相邻桶之间的插值即可。
注意由于间隔值可能小于1,因此需要取ceil函数,此为陷阱。
标签:
原文地址:http://www.cnblogs.com/ibuki/p/4826834.html