1 class Solution:
 2     def summaryRanges(self, nums: List[int]) -> List[str]:
 3         n = len(nums)
 4         if n == 0:
 5             return []
 6         pre = nums[0]
 7         res = [[nums[0],nums[0]]]
 8         for i in range(1,n):
 9             cur = nums[i]
10             if cur - pre == 1:
11                 pre = cur
12                 res[-1][1] = cur
13             else:
14                 pre = cur
15                 res.append([cur,cur])
16         result = []
17         for j in range(len(res)):
18             begin,end = res[j][0],res[j][1]
19             if begin == end:
20                 result.append(str(begin))
21             else:
22                 result.append(str(begin) + '->' + str(end))
23         return result

算法思路:数组遍历。

先记录每一段连续区间的[起始值,结束值]的数组,再生成对应格式的字符串数组。

posted on 2020-04-04 20:34  Sempron2800+  阅读(138)  评论(0编辑  收藏  举报