164. Maximum Gap【H】【80】【桶排序】【VIP】

175 篇文章 0 订阅
157 篇文章 0 订阅

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.

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question




注释掉的方法肯定是比较流氓的了。。

重点在于桶排序

这个思想还是很好用的

利用桶排序思想: 
假设有N个元素数组array,最大值为Max,最小值为Min。 
那么最大差值不会大于ceiling[(Maz - Min) / (N - 1)]。

令bucket(桶)的大小len = ceiling[(Maz - Min) / (N - 1)],则最多会有(Max - Min) / len + 1个桶 
对于数组中的任意整数K,很容易通过算式index = (K - Min) / len找出其桶的位置,然后维护每一个桶的最大值和最小值。


由于同一个桶内的元素之间的差值至多为len - 1,因此最终答案不会从同一个桶中选择。 
对于每一个非空的桶p,找出下一个非空的桶q,则q.min - p.max可能就是备选答案。返回所有这些可能值中的最大值。




class Solution(object):
    def maximumGap(self, nums):

        if len(nums) < 2:
            return 0

        a = min(nums)
        b = max(nums)
        if a == b:
            return 0

        size = math.ceil((b - a) / (len(nums) + 0.0) )
        #print size
        if size == 0:
            size = 1
        if size != int(size):
            size = int(size) + 1
        else:
            size = int(size)
        #print a,b,size,len(nums)

        bucketMin = [sys.maxint] * (len(nums) + 1)
        bucketMax = [0] * (len(nums) + 1)

        for i in nums:
            index = (i - a) / size
            #print index,i,size
            bucketMin[index] = min(bucketMin[index],i)
            bucketMax[index] = max(bucketMax[index],i)

        prv = bucketMax[0]
        res = 0
        for i in xrange(len(nums)):
            if bucketMin[i] == sys.maxint:
                continue
            res = max(bucketMin[i] - prv,res)
            prv = bucketMax[i]

        #print bucketMax,bucketMin

        #print res
        return res

        '''
        nums.sort()
        i = 0
        res = 0
        while i < len(nums) - 1:
            res = max(res,nums[i+1] - nums[i])
            i += 1
        return res
        '''


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值