Leetcode: 164. Maximum Gap

URL

https://leetcode.com/problems/maximum-gap/description/

描述

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.

解题思路

基本思路是桶排序。
步骤如下:
1. 遍历整个数组,求出最小值min,最大值max.
2. 求出平均每两个相邻的数字之间的平均差,(max-min)/(n-1)
这里解释一下,我们可以想象n个数字会有n-1个间隔,上面的公式会求出平均间隔的大小。
3. 接下来遍历数组把每一个数字放到相应的间隔中(这里的间隔就是桶,num[i] = min+ gap*k, 则把num[i]放入第K个桶中)。放入桶的时候我们只记录这个桶中的最小值和最大值。
4. 之后遍历所有桶, 在前一个桶的最大值和后一个桶的最小值的差值中找最大的差值。

代码示例

public int maximumGap(int[] nums) {

        if(nums==null) return 0;
        int len = nums.length;
        if(len ==0 || len == 1)
            return 0;
        if(len==2){
            return Math.abs(nums[0]-nums[1]);
        }
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        for(int num:nums){
            min = Math.min(num,min);
            max = Math.max(num,max);
        }

        if(min==max) return 0;

        int everageGap = (max-min)/ (len-1) +1;

        int[] bucketMin = new int[len];
        int[] bucketMax = new int[len];

        Arrays.fill(bucketMin,Integer.MAX_VALUE);
        Arrays.fill(bucketMax,Integer.MIN_VALUE);

        int idx = 0;
        for(int num: nums){
            idx = (num - min)/everageGap;
            bucketMin[idx] = Math.min(num,bucketMin[idx]);
            bucketMax[idx] = Math.max(num,bucketMax[idx]);
        }

        int res = Integer.MIN_VALUE;
        int lastMax = -1;
        for(int i=0;i<len;i++){
            if(bucketMin[i]==Integer.MAX_VALUE){
                continue;
            }
            if(lastMax != -1){
                res = Math.max(res,bucketMin[i] - lastMax);
            }
            lastMax = bucketMax[i];
        }

        return res;
     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值