Easy to understand Python


  • 0
    C

    If we don't want to deal with the situation when i == len(nums) - 1, we can add on element at the end like nums.append(nums[-1] + 2)

    class Solution(object):
        def summaryRanges(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            if not nums:
                return []
            #nums.append(nums[-1] + 2)
            res = []
            start = 0
            for i in range(1, len(nums)):
                if nums[i] - nums[i-1] != 1:
                    if i - 1 == start:
                        res.append(str(nums[start]))
                    else:
                        res.append(str(nums[start]) + "->" + str(nums[i - 1]))
                    start = i
            if start == len(nums) - 1:
                res.append(str(nums[start]))
            else:
                res.append(str(nums[start]) + "->" + str(nums[len(nums) - 1]))
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.