-
Notifications
You must be signed in to change notification settings - Fork 0
/
汇总区间.py
40 lines (30 loc) · 1.09 KB
/
汇总区间.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
class Solution:
def summaryRanges(self, nums: list[int]) -> list[str]:
if not nums:
return []
ranges = []
start = nums[0]
end = nums[0]
for n in nums[1:]:
# 如果当前数字与前一个数字连续,则更新区间的结束数字
if n == end + 1:
end = n
else:
# 如果当前数字与前一个数字不连续,结束当前区间,并开始一个新区间
if start == end:
ranges.append(str(start))
else:
ranges.append("{}->{}".format(start, end))
# 更新起始区间
start = n
end = n
# 添加最后一个区间
if start == end:
ranges.append(str(start))
else:
ranges.append("{}->{}".format(start, end))
return ranges
# 示例测试
sol = Solution()
print(sol.summaryRanges([0,1,2,4,5,7])) # 输出:["0->2","4->5","7"]
print(sol.summaryRanges([0,2,3,4,6,8,9])) # 输出:["0","2->4","6","8->9"]