[leetcode] Maximum Gap

本文介绍了一种使用桶排序原理解决LeetCode上的最大间隔问题的方法。该算法通过将数组中的元素分配到相应的桶中,并记录每个桶的最大和最小值来找到排序后数组中连续元素之间的最大差值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

From : https://leetcode.com/problems/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.

思路 : 

用桶排序原理,将n个数放入n个桶中,记录每个桶中的最大和最小值。

如果n个数分别在n个桶中,那么后一桶的最大(同时也是最小)与前一桶的最小(同时也是最大)之差的最大就是maxGap; 否则,如果n个数不全在n个桶中,那么必然有空桶,空桶后一个的最小和前一个的最大的差必然比桶的长度达,那么后桶最小和前桶最大之差的最大仍然是maxGap。

综上所述,取 max{buckets[0].max-buckets[0].min,  buckets[n-1].max-buckets[n-1].min,  max {buckets[i].min-buckets.max}} , 即buckets[0].max-buckets[0].min   ,  buckets[n-1].max-buckets[n-1].min 和 max {buckets[i].min-buckets.max}的最大值。

public class Solution {
    
    class Bucket {
        // if min < 1, the bucket is empty
        int min = -1;
        int max;
    }
    
    public int maximumGap(int[] nums) {
        if(nums.length < 2) {
            return 0;
        }
        int len = nums.length;
        int gmax = nums[0], gmin = gmax;
        for(int i=1; i<len; ++i) {
            int c = nums[i];
            if(c < gmin) {
                gmin = c;
            } else if(c > gmax) {
                gmax = c;
            }
        }
        
        int size = (int) Math.ceil( (double)(gmax - gmin + 1) / (double)len );
        Bucket[] buckets = new Bucket[len]; // len buckets
        for(int i=0; i<len; ++i) {
        	buckets[i] = new Bucket();
        }
        for(int num : nums) {
            Bucket bucket = buckets[(num-gmin)/size];
            if(bucket.min < 0) {
                // empty bucket
                bucket.min = bucket.max = num;
            } else {
                if(num < bucket.min) {
                    bucket.min = num;
                } else if(num > bucket.max) {
                    bucket.max = num;
                }
            }
        }
        
        int min = buckets[0].min, max=min, maxGap = buckets[0].max-min;
        for(Bucket b : buckets) {
            if(b.min < 0) {
                continue;
            }
            min = b.min;
            if(min - max > maxGap) {
                maxGap = min-max;
            }
            max = b.max;
        }
        
        return gmax-min > maxGap ? gmax-min : maxGap;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值