Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example
Example 1:
Input: [1, 9, 2, 5]
Output: 4
Explanation: The sorted form is [1, 2, 5, 9], and the maximum gap is between 5 and 9.
Example 2:
Input: [1]
Output: 0
Explanation: The array contains less than 2 elements.
Challenge
Sort is easy but will cost O(nlogn) time. Try to solve it in linear time and space.
Notice
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
思路:bucket sort.核心思想就是:求出min, max之后还剩下n-2 个数,如果我们divide into n-1 个bucket的话,肯定有一个bucket是空,那么 [min1, max1] [ 空] [min2,max2] 那么,gap的最大值就是min2 - max1;
写代码的时候,注意开两个数组,然后bucket Num可以设置的更大一点,没关系,只要有空的就行;另外Long 数组用来避开数组里面有Integer.MAX_VALUE 或者Integer.MIN_VALUE的情况;
public class Solution {
/**
* @param nums: an array of integers
* @return: the maximun difference
*/
public int maximumGap(int[] nums) {
if(nums == null || nums.length < 2) return 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int n = nums.length;
for(int i = 0; i < n; i++) {
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);
}
int gap = (max - min) / n + 1;
// bucket number其实还可以设置更大点,没关系,
// 只要保证最后落入的数字,中间bucket有空就行;
int bucketNum = (max - min) / gap + 1;
Long[] minBucket = new Long[bucketNum];
Long[] maxBucket = new Long[bucketNum];
Arrays.fill(minBucket, Long.MAX_VALUE);
Arrays.fill(maxBucket, Long.MIN_VALUE);
for(int i = 0; i < nums.length; i++) {
int index = ((nums[i] - min) / gap);
minBucket[index] = Math.min(minBucket[index], nums[i]);
maxBucket[index] = Math.max(maxBucket[index], nums[i]);
}
int pre = 0;
long res = 0;
for(int i = 0; i < bucketNum; i++) {
if(minBucket[i] != Long.MAX_VALUE) {
res = Math.max(res, minBucket[i] - maxBucket[pre]);
pre = i;
}
}
return (int)res;
}
}