forked from nyuhuyang/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-gap.py
82 lines (69 loc) · 2.27 KB
/
maximum-gap.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Time: O(n)
# Space: O(n)
# 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.
# bucket sort
# Time: O(n)
# Space: O(n)
class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return 0
# Init bucket.
max_val, min_val = max(nums), min(nums)
gap = max(1, (max_val - min_val) / (len(nums) - 1))
bucket_size = (max_val - min_val) / gap + 1
bucket = [{'min':float("inf"), 'max':float("-inf")} \
for _ in xrange(bucket_size)]
# Find the bucket where the n should be put.
for n in nums:
# min_val / max_val is in the first / last bucket.
if n in (max_val, min_val):
continue
i = (n - min_val) / gap
bucket[i]['min'] = min(bucket[i]['min'], n)
bucket[i]['max'] = max(bucket[i]['max'], n)
# Count each bucket gap between the first and the last bucket.
max_gap, pre_bucket_max = 0, min_val
for i in xrange(bucket_size):
# Skip the bucket it empty.
if bucket[i]['min'] == float("inf") and \
bucket[i]['max'] == float("-inf"):
continue
max_gap = max(max_gap, bucket[i]['min'] - pre_bucket_max)
pre_bucket_max = bucket[i]['max']
# Count the last bucket.
max_gap = max(max_gap, max_val - pre_bucket_max)
return max_gap
# Time: O(nlogn)
# Space: O(n)
class Solution2(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return 0
nums.sort()
pre = nums[0]
max_gap = float("-inf")
for i in nums:
max_gap = max(max_gap, i - pre)
pre = i
return max_gap
if __name__ == "__main__":
print Solution().maximumGap([3, 1, 1, 1, 5, 5, 5, 5])