使用双指针,维护left和right两个指针,使用两个while循环分别前进两个指针
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
if not nums:
return []
n = len(nums)
if n == 1:
return [str(nums[0])]
left, right = 0, 0
res = []
while left < n:
while right < n-1 and nums[right+1] == nums[right] + 1:
right += 1
if left == right:
res.append(str(nums[right]))
else:
res.append(str(nums[left])+'->'+str(nums[right]))
left = right + 1
right = left
return res