164. 最大间距(困难,数组)(12.24)

给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。

如果数组元素个数小于 2,则返回 0。

示例 1:

输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。

示例 2:

输入: [10]
输出: 0
解释: 数组元素个数小于 2,因此返回 0。
class Solution(object):
    def maximumGap(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums)==1:
            return 0
        s=sorted(nums)
        result=0
        for i in range(1,len(nums)):
            if (s[i]-s[i-1])>result:
                result=s[i]-s[i-1]
        return result

执行用时: 32 ms, 在Maximum Gap的Python提交中击败了80.39% 的用户

注意:数组用sorted()、列表用.sort()

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/85237866