forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
summary-ranges.py
40 lines (36 loc) · 1.06 KB
/
summary-ranges.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
# Time: O(n)
# Space: O(1)
#
# Given a sorted integer array without duplicates,
# return the summary of its ranges.
#
# For example, given [0,1,2,4,5,7],
# return ["0->2","4->5","7"].
#
class Solution:
# @param {integer[]} nums
# @return {string[]}
def summaryRanges(self, nums):
ranges = []
if not nums:
return ranges
start, end = nums[0], nums[0]
for i in xrange(1, len(nums) + 1):
if i < len(nums) and nums[i] == end + 1:
end = nums[i]
else:
interval = str(start)
if start != end:
interval += "->" + str(end)
ranges.append(interval)
if i < len(nums):
start = end = nums[i]
return ranges
# Time: O(n)
# Space: O(n)
class Solution2:
# @param {integer[]} nums
# @return {string[]}
def summaryRanges(self, nums):
return [re.sub('->.*>', '->', '->'.join(`n` for _, n in g))
for _, g in itertools.groupby(enumerate(nums), lambda (i, n): n-i)]