题目:
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.
题解:
桶排序(bucket sort)
假设有N个元素A到B.
bucket(桶)的大小bucketLen = max(1,(B - A) / (N - 1)), 注意bucketLen为0的情况,则最多会有(B - A) / bucketLen + 1个桶
对于数组中的任意整数K, 很容易通过算式loc = (K - A) / bucketLen找出其桶的位置,然后维护每一个桶的最大值和最小值
由于同一个桶内的元素之间的差值至多为bucketLen - 1,因此最终答案不会从同一个桶中选择,否则整体的range达不到B-A.
对于每一个非空的桶p,找出下一个非空的桶q,则q.min - p.max可能就是备选答案。返回所有这些可能值中的最大值。
Note: corner case [1,1,1,1]若元素都相同,range就是0,16行算bucket时需要保持bucket的长度大于等于1.否则17行就有除以0的error.
同时此情况maxGap = 0. 所以maxGap的初始化是0而不是Integer.MIN_VALUE.
Time Complexity: O(n).
Space O(n).
AC Java:
1 public classSolution {2 public int maximumGap(int[] nums) {3 if(nums == null || nums.length < 2){4 return 0;5 }6 //Calculate the range
7 int max =Integer.MIN_VALUE;8 int min =Integer.MAX_VALUE;9 int len =nums.length;10 for(int i = 0; i
15 //bucket length and number
16 int bucketLen = Math.max(1,(max-min)/(len-1)); //error
17 int buckNum = (max-min)/bucketLen + 1;18
19 //calculate nums[i] position in buckets and maintain the maximun and minmum of each bucket
20 int [] maxArr = new int[buckNum];21 int [] minArr = new int[buckNum];22 Arrays.fill(maxArr, Integer.MIN_VALUE);23 Arrays.fill(minArr, Integer.MAX_VALUE);24 for(int i = 0; i
30 int maxGap = 0;31 int preMax = maxArr[0];32 for(int i = 1; i