Maximum Gap

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.

Solution 1:O(n*logn)

public class Solution {
    public int maximumGap(int[] nums) {
        int len=nums.length;
        if(len<2)
            return 0;
        int gap=0;
        Arrays.sort(nums);
        for(int i=0;i<len-1;++i){
            int temp=nums[i]-nums[i+1]>0?nums[i]-nums[i+1]:nums[i+1]-nums[i];
            if(temp>gap)
                gap=temp;
        }
        return gap;
    }
}

Solution 2:O(n) Find in discuss:Use bucket sort:

public class Solution {
    public int maximumGap(int[] nums) {
        int n=nums.length;
        if(n<2)
            return 0;
        int max=nums[0];
        int min=nums[0];
        for(int i:nums){
            max=Math.max(max,i);
            min=Math.min(min,i);
        }
        int gap=(int)Math.ceil((double)(max-min)/(n-1));
        int[] bucketmaxs=new int[n-1];
        int[] bucketmins=new int[n-1];
        Arrays.fill(bucketmaxs,Integer.MIN_VALUE);
        Arrays.fill(bucketmins,Integer.MAX_VALUE);
        for(int i:nums){
            if(i==min||i==max)
                continue;
            int index=(i-min)/gap;
            bucketmaxs[index]=Math.max(i,bucketmaxs[index]);
            bucketmins[index]=Math.min(i,bucketmins[index]);
        }
        int pre=min;
        int maxgap=Integer.MIN_VALUE;
        for(int i=0;i<n-1;++i){
            if(bucketmins[i]==Integer.MAX_VALUE&&bucketmaxs[i]==Integer.MIN_VALUE)
                continue;
            maxgap=Math.max(maxgap,bucketmins[i]-pre);
            pre=bucketmaxs[i];
        }
        maxgap=Math.max(maxgap,max-pre);
        return maxgap;
    
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值