美文网首页
164. Maximum Gap

164. Maximum Gap

作者: codingXue | 来源:发表于2016-09-28 10:48 被阅读41次

    问题描述

    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.

    问题分析

    又是一道hard题,上来直接没思路呀。
    参考了网上的解题报告,是利用桶排序的思想。
    最关键的一点是,设数组中有n个元素,其中最大值为b,最小值为a,则排序后相邻两个元素的差值不会小于⌈(b-a) / (n-1)⌉
    因此做法为,设置桶的大小为size = ⌈(b-a) / (n-1)⌉,那么桶的个数为(b-a) / size + 1;遍历数组,对每个桶记录其最大值和最小值;最后遍历一遍桶,最大的gap不会出现在桶的内部,而在桶之间,因此获得“后一个非空桶的最小值减前一个非空桶的最大值”的最大值,即为要求的值。

    AC代码

    class Solution(object):
        def maximumGap(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            n = len(nums)
            if n < 2:
                return 0
            b = a = nums[0]
            for i in nums:
                if i > b:
                    b = i
                if i < a:
                    a = i
            if a == b:
                return 0
            size = (b-a) / (n-1)
            if (b-a) % (n-1) != 0:
                size += 1
            num = (b-a) / size + 1
            bucket_b = [None for i in range(num)]
            bucket_a = [None for i in range(num)]
            for i in nums:
                bucket = (i-a)/size
                if not bucket_b[bucket] or i > bucket_b[bucket]:
                    bucket_b[bucket] = i
                if not bucket_a[bucket] or i < bucket_a[bucket]:
                    bucket_a[bucket] = i
            gap = 0
            p = 0
            while True:
                q = p+1
                while q < num and not bucket_a[q]:
                    q += 1
                if q == num:
                    break
                if gap < bucket_a[q] - bucket_b[p]:
                    gap = bucket_a[q] - bucket_b[p]
                p = q
    
            return gap
    

    Runtime: 59 ms, which beats 83.05% of Python submissions.

    相关文章

      网友评论

          本文标题:164. Maximum Gap

          本文链接:https://www.haomeiwen.com/subject/wtmhyttx.html