-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path228.py
More file actions
72 lines (66 loc) · 2.22 KB
/
228.py
File metadata and controls
72 lines (66 loc) · 2.22 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
'''
228. Summary Ranges
https://leetcode.com/problems/summary-ranges/
Hi, here's your problem today.
This problem was recently asked by Facebook:
Given a sorted list of numbers,
return a list of strings that represent all of the consecutive numbers.
Example:
Input: [0, 1, 2, 5, 7, 8, 9, 9, 10, 11, 15]
Output: ['0->2', '5', '7->11', '15->15']
Assume that all numbers will be greater than or
equal to 0, and each element can repeat.
'''
from typing import *
#Ugly
def findRanges(nums):
result = []
start = 0
for i in range(1,len(nums)):
if nums[i]!=nums[i-1] and nums[i]!=nums[i-1]+1:
if start==i-1:
result.append("{}".format(nums[start]))
else:
result.append("{}->{}".format(nums[start], nums[i-1]))
start = i
if nums:
if start==len(nums)-1:
result.append("{}".format(nums[start]))
else:
result.append("{}->{}".format(nums[start], nums[-1]))
return result
#Good
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
result = []
start,n = 0, len(nums)
while start < n:
end = start+1
while end<n and \
(nums[end]==nums[end-1] or \
nums[end]==nums[end-1]+1):
end += 1
if start==(end-1):
result.append("{}".format(nums[start]))
else:
result.append("{}->{}".format(nums[start], nums[end-1]))
start = end
return result
class AnotherSolution:
def summaryRanges(self, nums: List[int]) -> List[str]:
summary = []
idx = 0
while idx < len(nums):
start = idx
cnt = 1
while start+cnt<len(nums) and \
nums[start+cnt]==nums[start+cnt-1]+1:
cnt += 1
if cnt == 1:
summary.append("{}".format(nums[start]))
else:
summary.append("{}->{}".format(nums[start], nums[start+cnt-1]))
idx += cnt
return summary
print(Solution().summaryRanges([0, 1, 2, 5, 7, 8, 9, 9, 10, 11, 15]))
# ['0->2', '5', '7->11', '15->15']