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.

这里讲的很清楚:https://github.com/tg123/leetcode/tree/gh-pages/maximum-gap


中心思想就是bucket sort。把元素分别放到不同的bucket里面,每一个bucket维护最大最小值。当前bucket的最小值和上一个bucket的最大值就形成了一个gap。

不知道原创是怎么想出来的。。。

public class Solution {
    
    private class Bucket {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        public void add(int num) {
            min = Math.min(min, num);
            max = Math.max(max, num);
        }
    }

    public int maximumGap(int[] num) {
        if (num.length < 2) {
            return 0;
        }
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < num.length; i++) {
            min = Math.min(num[i], min);
            max = Math.max(num[i], max);
        }
        int gap = (int)Math.ceil((double)(max-min)/(num.length-1));
        Bucket[] buckets = new Bucket[num.length];
        int maxGap = 0;
        for (int i = 0; i < num.length; i++) {
            int ind = (num[i]-min)/gap;
            if (buckets[ind] == null) {
                buckets[ind] = new Bucket();
            }
            buckets[ind].add(num[i]);
        }

        Bucket lastBucket = null;
        for (int i = 0; i < num.length; i++) {
            if (lastBucket != null && buckets[i] != null) {
                maxGap = Math.max(maxGap, buckets[i].min-lastBucket.max);
            }
            if(buckets[i] != null) {
                lastBucket = buckets[i];
            }
        }
        return maxGap;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值