leetcode 164. Maximum Gap

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值