边工作边刷题:70天一遍leetcode: day 4

Maximum Gap

要点:
问题:

  • 为什么用n(元素个数)作为bucket的个数?
  • 为什么用range公式

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.


class Solution(object):
    def maximumGap(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        maxv = -sys.maxint-1
        minv = sys.maxint
        n = len(nums)
        if n==0: return 0
        buckets = [[None, None] for i in range(n)]
        for i in range(n):
            maxv = max(maxv, nums[i])
            minv = min(minv, nums[i])
        
        r = (maxv-minv)/n+1
        for i in range(n):
            bn = (nums[i]-minv)/r
            if not buckets[bn][0] or buckets[bn][0]>nums[i]:
                buckets[bn][0]=nums[i]
                
            if not buckets[bn][1] or buckets[bn][1]<nums[i]:
                buckets[bn][1]=nums[i]
        
        gap = 0
        pre = buckets[0][1]
        for i in range(1, n):
            if buckets[i][0]:
                gap = max(gap, buckets[i][0]-pre)
                pre = buckets[i][1]
        
        return gap
原文地址:https://www.cnblogs.com/absolute/p/5554996.html