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

来源:互联网 发布:数据库应用系统的构成 编辑:程序博客网 时间:2024/05/22 16:42

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        '''


0 0
原创粉丝点击