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 1:
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Note:
- You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
- Try to solve it in linear time/space.
题目找出未排序数组排序后相邻数字的最大差值。
提示要求是线性的复杂度。显然是无法完全进行排序的。参考抽屉原理和桶排序。我们可以设计一个桶排序结构,使得最大差值一定在桶之间。而桶内部就不需要排序了,只需要记录最大值和最小值。这样可以做到线性解题。代码如下:
int max(int n1,int n2){
return n1>n2?n1:n2;
}
struct Node{
int max;
int min;
int num;
};
int maximumGap(int* nums, int numsSize) {
if(numsSize <= 1) {
return 0;
}
if(numsSize == 2){
return nums[1] >nums[0]?nums[1]-nums[0]:nums[0]-nums[1];
}
int maxN = nums[0];
int minN = maxN;
for(int i = 1 ;i < numsSize;++i){
if(nums[i] > maxN){
maxN = nums[i];
}else if(nums[i] < minN){
minN = nums[i];
}
}
if(maxN - minN <= 1){
return maxN - minN;
}
int minMax = (maxN-minN)/(numsSize-1);
if(minMax == 0){
minMax = 1;
}
//更具最大值最小值差,和数字个数,确定桶的大小和数量。
int bucketWidth = minMax;
int bucketNum = (maxN-minN)/bucketWidth+1;
struct Node bucket[bucketNum];
memset(bucket,0,sizeof(bucket));
for(int i = 0; i < numsSize;++i){
int num = nums[i];
int bucketIndex = (num-minN)/bucketWidth;
if(bucket[bucketIndex].num == 0){
bucket[bucketIndex].num = 1;
bucket[bucketIndex].max = bucket[bucketIndex].min = num;
}else{
if(num < bucket[bucketIndex].min){
bucket[bucketIndex].min = num;
}else if(num > bucket[bucketIndex].max){
bucket[bucketIndex].max = num;
}
}
}
int maxDif = 0;
int start = bucket[0].max;
for(int i = 1;i < bucketNum;++i){
if(bucket[i].num != 0){
maxDif = max(maxDif,bucket[i].min-start);
start = bucket[i].max;
}
}
return maxDif;
}