1、题目描述
https://leetcode-cn.com/problems/maximum-gap/
给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
如果数组元素个数小于 2,则返回 0。
输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
输入: [10]
输出: 0
解释: 数组元素个数小于 2,因此返回 0。
- 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
- 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。
2、代码详解
class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums) < 2:
return 0
max_num = max(nums)
min_num = min(nums)
max_subtraction = 0 # 差值
each_bucket_len = max(1, (max_num-min_num)//(len(nums)-1))
buckets = [[] for _ in range((max_num-min_num) // each_bucket_len + 1)]
for i in range(len(nums)):
loc = (nums[i]-min_num)//each_bucket_len
buckets[loc].append(nums[i])
prev_max = float('inf')
for i in range(len(buckets)):
if buckets[i] and prev_max != float('inf'):
max_subtraction = max(max_subtraction, min(buckets[i])-prev_max)
if buckets[i]:
prev_max = max(buckets[i])
return max_subtraction
s = Solution()
nums = [3, 6, 9, 1]
print(s.maximumGap(nums))
https://leetcode-cn.com/problems/maximum-gap/solution/python3-tong-pai-xu-by-yanghk/