LeetCode-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.
Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.
给定一个未排序的数组,求在这个数组排好序的情况下,相邻两个元素的最大差值。要求是O(n)的时间和空间复杂度。
涉及到排序,又要求O(n)的时间复杂度,自然就想到了桶排。但是如何划分桶呢。
1. 假设数组最大元素是max,最小元素是min,数组长度是length,
则最大差值maxGap必须满足maxGap >= Math.ceil((max-min) / length-1);
桶的个数满足bucketCount = (max-min) / minMaxGap + 1;
第k个桶的范围表示[min+(k-1)*maxGap, min+k*maxGap) 注意区间的开闭;
2. 我们将数组的元素按照大小放在对应的桶当中
3. 放置好数组元素后,需要寻找最大的差值,按照上面的划分,则最大的差值应该出现在不同的桶之间。
代码如下:
public int maximumGap(int[] nums) { if(nums == null || nums.length < 2) return 0; int min = nums[0]; int max = nums[0]; for(int i=1; i<nums.length; i++) { if(nums[i] < min) min = nums[i]; else if(nums[i] > max) max = nums[i]; } int minMaxGap = (int)Math.ceil((double)(max-min) / (nums.length-1)); int bucketCount = (max-min) / minMaxGap + 1; int[][] bucket = new int[bucketCount][2]; for(int i=0; i<nums.length; i++) { int position = (nums[i]-min) / minMaxGap; if(nums[i] < bucket[position][0] || bucket[position][0] < min || position > 0 && bucket[position][0] == min) bucket[position][0] = nums[i]; if(nums[i] > bucket[position][1]) bucket[position][1] = nums[i]; } int maxGap = 0; int lastMax = bucket[0][1]; for(int i=1; i<bucketCount; i++) { if(bucket[i][0] > min) { maxGap = Math.max(maxGap, bucket[i][0] - lastMax); lastMax = bucket[i][1]; } } return maxGap; }
posted on 2015-05-13 11:39 linxiong1991 阅读(255) 评论(0) 编辑 收藏 举报