Python solution with comments


  • 1
    P
    class Solution(object):
        def summaryRanges(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            ans = []
            for i in range(len(nums)):
                # We are on the 1st number OR the number is not continuous with the previous number in nums
                if i == 0 or nums[i] != nums[i-1] + 1:
                    ans.append(str(nums[i]))
                # We are on the last number AND the number is not continuous with the previous number in nums
                elif i == len(nums) - 1 and nums[i] != nums[i-1] + 1:
                    ans.append(str(nums[i]))
                # We are on the last number AND the number is continuous with the previous number in nums
                elif i == len(nums) - 1 and nums[i] == nums[i-1] + 1:
                    ans[len(ans)-1] += '->' + str(nums[i])
                # The number we are on is not continuous with the next number in nums
                elif nums[i] != nums[i+1] - 1:
                    ans[len(ans)-1] += '->' + str(nums[i])
                
            return ans
    

Log in to reply
 

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