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

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

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值