美文网首页
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.

相关文章

  • 2019-01-16

    LeetCode 164. Maximum Gap Description Given an unsorted a...

  • ARTS 第20周

    ARTS 第20周分享 [TOC] Algorithm 164. Maximum Gap [hard] [题目描述...

  • 164. Maximum Gap

    问题描述 Given an unsorted array, find the maximum difference...

  • Leetcode 164. Maximum Gap

    Given an unsorted array, find the maximum difference betw...

  • LeetCode 164. Maximum Gap

    Description Given an unsorted array, find the maximum dif...

  • 164. Maximum Gap(最大间距)

    题目 LeetCode中文站 解答 根据题意我们就可以直到这是一题先排序,然后再寻找最大间距的题目,我们先使用最简...

  • Maximum Gap

    https://leetcode.com/problems/maximum-gap/给定一个无序int数组,求出排...

  • Leetcode - Maximum Gap

    My code: 看到这道题目,第一个想法是排序。然后要求排序时间复杂度是 O(n)就想到了 radix sort...

  • LintCode 最大间距

    http://www.lintcode.com/zh-cn/problem/maximum-gap/ 最大间距 查...

  • Leetcode-164-Maximum Gap

    给定一个未排序的数组,求排序后数组中相邻元素之差的最大值。 这题最大的思维盲点就在于的复杂度让人直接放弃包含排序的...

网友评论

      本文标题:164. Maximum Gap

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