Simple python solution, avoid corner case by easy trick


  • 0
    Y
    class Solution(object):
        def findMissingRanges(self, nums, lower, upper):
            """
            :type nums: List[int]
            :type lower: int
            :type upper: int
            :rtype: List[str]
            """
            if len(nums) == 0:
                nums.append(lower-1)
                nums.append(upper+1)
            if nums[0] > lower:
                nums.insert(0, lower-1) #the trick here is to expand the boundary for 1
            if nums[-1] < upper:
                nums.append(upper+1)
            res = []
            s = 0 #slower pointer
            for i in xrange(0, len(nums)-1):
                if nums[i+1] - nums[i] != 1:
                    s = i
                    if nums[s]+1 == nums[i+1]-1:
                        res.append(str(nums[s]+1))
                    else:
                        res.append(str(nums[s]+1)+"->"+str(nums[i+1]-1))
            return res
    

Log in to reply
 

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