您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页164. Maximum Gap

164. 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.

问题分析

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.

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务