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.

这题是求排序后的相邻数字之间的最大差.但是题意要求用O(n)的解法和空间来解决,单纯的使用quicksort等方法无法满足复杂度的要求.

可以考虑桶排序,基数排序等O(n)的排序方法.这里用桶排, 用average gap = (max - min)/(n-1)+1作为桶的大小.这样每个桶内的数组之间的gap不可能超过最大gap.考虑每个桶之间的gap,即前一个桶的最大值和当前桶的最小值之间的差可能成为Maximum Gap.这里的做法是不把最大值,最小值放入桶内,这样比较好的避免了只有两个数字时,只有一个桶或者为等差数列时average gap大于最大gap的情况.

class Solution(object):
    def maximumGap(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums or len(nums) < 2:
            return 0
        #first step, find the min and max value
        minVal = nums[0]
        maxVal = nums[0]
        for i in xrange(1,len(nums)):
            minVal = min(minVal, nums[i])
            maxVal = max(maxVal, nums[i])
        #bucket sort, calculate the gap, average gap  between the numbers. the final answer is large than it
        gap = (maxVal - minVal)/(len(nums)-1) + 1
        #initialize the bucket value
        bucket_num = (maxVal - minVal)/gap + 1
        bucket_min = [2**31-1] * bucket_num #32bit signed int
        bucket_max = [0] * bucket_num
        for i in nums:
            if i == minVal or i == maxVal:  #不把最大值和最小值放入桶中
                continue
            index = (i - minVal)/gap #right postion of the bucket, because the really index must start from 0
            #find each bucket's bottom value and top value
            bucket_min[index] = min(bucket_min[index], i)
            bucket_max[index] = max(bucket_max[index], i)
        previous = minVal
        res = 0
        for j in xrange(bucket_num):
            if bucket_min[j] == 2**31-1 and bucket_max[j] == 0 : continue #防止桶空
            res = max(res, bucket_min[j] - previous)
            previous = bucket_max[j]
        res = max(res, maxVal - previous)
        return res
        

 

posted on 2016-07-23 20:00  Sheryl Wang  阅读(143)  评论(0编辑  收藏  举报

导航