228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input: [0,1,2,4,5,7]
Output: [“0->2”,“4->5”,“7”]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input: [0,2,3,4,6,8,9]
Output: [“0”,“2->4”,“6”,“8->9”]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

思路

利用一个循环,判断是否符合要求:nums[i+1] - nums[i] == 1,如果符合就继续判断,否则就把值放入list中。

python

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        res = []
        i = 0
        while i < len(nums):
            tmp = nums[i]
            while i < len(nums)-1 and nums[i] == nums[i + 1] - 1:
                i += 1
            if tmp != nums[i]:
                res.append(str(tmp) + "->" + str(nums[i]))
            else:
                res.append(str(tmp))
            i += 1
        return res