leetcode-228题:summary ranges

题目

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”].

思路

用两个指针来确定一个区间

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
res = []
l = 0
while l < len(nums):
r = l
while r+1<len(nums) and (nums[r+1]-nums[r])==1:
r += 1
if l == r:
res.append(str(nums[l]))
l += 1
else:
res.append(str(nums[l])+'->'+str(nums[r]))
l = r+1
return res