forked from shijbian/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-gap.py
More file actions
79 lines (68 loc) · 2.17 KB
/
Copy pathmaximum-gap.py
File metadata and controls
79 lines (68 loc) · 2.17 KB
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
# 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
class Solution:
# @param num, a list of integer
# @return an integer
def maximumGap(self, num):
if len(num) < 2:
return 0
unique_num = self.removeDuplicate(num)
max_val, min_val = max(unique_num), min(unique_num)
gap = (max_val - min_val) / (len(unique_num) - 1)
bucket_size = (max_val - min_val) / gap + 1
max_bucket = [float("-inf") for _ in xrange(bucket_size)]
min_bucket = [float("inf") for _ in xrange(bucket_size)]
for i in unique_num:
if i in (max_val, min_val):
continue
idx = (i - min_val) / gap
max_bucket[idx] = max(max_bucket[idx], i)
min_bucket[idx] = min(min_bucket[idx], i)
max_gap = 0
pre = min_val
for i in xrange(bucket_size):
if max_bucket[i] == float("-inf") and min_bucket[i] == float("inf"):
continue
max_gap = max(max_gap, min_bucket[i] - pre)
pre = max_bucket[i]
max_gap = max(max_gap, max_val - pre)
return max_gap
def removeDuplicate(self, num):
dict = {}
unique_num = []
for i in num:
if i not in dict:
unique_num.append(i)
dict[i] = True
return unique_num
# Time: O(nlogn)
# Space: O(n)
class Solution2:
# @param num, a list of integer
# @return an integer
def maximumGap(self, num):
if len(num) < 2:
return 0
num.sort()
pre = num[0]
max_gap = float("-inf")
for i in num:
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])