leetcode 164: Maximum Gap

本文介绍了一种用于寻找整数数组中最大数值间隔的高效算法。该算法通过将数据分布到多个桶(bucket)中来实现,每个桶记录其内部的最大值和最小值。这种方法避免了直接排序,减少了计算复杂度。

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

Very hard problem, if I didn't learn the algorithm first, I will never think of it. The idea is to divide the range max-min into some buckets. And assign all numbers to those buckets, then those numbers are already in order in the buckets. Finally scan the buckets and find out the maximum gap.

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        if(nums.size()<2)
            return 0;
        int len=nums.size();
        int Max=INT_MIN,Min=INT_MAX;
        for(int i=0;i<len;i++)
        {
            if(nums[i]>Max)
                Max=nums[i];
            if(nums[i]<Min)
                Min=nums[i];
        }
        int bsize=ceil((double)(Max-Min)/(len-1));//bucket size
        int bnum=ceil((double)(Max-Min)/bsize)+1;//number of buckets
        vector<pair<int,int> > buckets(bnum,make_pair(INT_MIN,INT_MAX));
        for(int i=0;i<len;i++)
        {
            int idx=(nums[i]-Min)/bsize;//get the index of bucket this number should be
            if(buckets[idx].first<nums[i])//update the max of the bucket
                buckets[idx].first=nums[i];
            if(buckets[idx].second>nums[i])//update the min of the bucket
                buckets[idx].second=nums[i];
        }
        int res=INT_MIN,pre=0;
        for(int curr=1;curr<buckets.size();curr++)
        {
            if(buckets[curr].first==INT_MIN)//empty bucket
                continue;
            res=max(res,buckets[curr].second-buckets[pre].first);
            pre=curr;
        }
        return res;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值