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.
Solution
假设有N个元素A到B。
那么最大差值不会大于于ceiling[(B - A) / (N - 1)]
令bucket(桶)的大小len = ceiling[(B - A) / (N - 1)],则最多会有(B - A) / len + 1个桶
对于数组中的任意整数K,很容易通过算式loc = (K - A) / len找出其桶的位置,然后维护每一个桶的最大值和最小值
由于同一个桶内的元素之间的差值至多为len - 1,因此最终答案不会从同一个桶中选择。
对于每一个非空的桶p,找出下一个非空的桶q,则q.min - p.max可能就是备选答案。返回所有这些可能值中的最大值。
(Maximum-Gap.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
N = len(nums)
if N < 2:
return 0
A = min(nums)
B = max(nums)
# 一个bucket的数值范围
bucketRange = max(1, int((B-A-1)/(N-1)) + 1)
# bucket数组的长度
bucketLen = (B-A) / bucketRange + 1
# bucket数组
buckets = [None]* bucketLen
# 把nums中的数都放到bucket中
for K in nums:
# 找到K在哪个bucket里
loc = (K-A)/bucketRange
bucket = buckets[loc]
if bucket is None:
# 每一个bucket只维护在这个bucket中的数的最大和最小值
bucket = {'min' : K, 'max' : K}
buckets[loc] = bucket
else:
bucket['min'] = min(bucket['min'], K)
bucket['max'] = max(bucket['max'], K)
maxGap = 0
for x in range(bucketLen):
if buckets[x] != None:
# next bucket的位置
y = x+1
# 找到一个飞空的bucket
while y < bucketLen and buckets[y] == None:
y += 1
if y < bucketLen:
maxGap = max(maxGap, buckets[y]['min'] - buckets[x]['max'])
x = y
return maxGap
|