Python solution supporting the case when lower > nums[0] or upper < nums[-1]


  • 0
    N
    class Solution(object):
        
        def addRange(self, s, e):
            if s == e:
                self.results.append(str(s))
            else:
                self.results.append("{0}->{1}".format(s, e))
        
        def findMissingRanges(self, nums, lower, upper):
            """
            :type nums: List[int]
            :type lower: int
            :type upper: int
            :rtype: List[str]
            """
            self.results = []
            si = 0
            while si < len(nums) and nums[si] < lower:
                si += 1
            while si < len(nums) and lower <= upper:
                if nums[si] == lower:
                    si += 1
                    lower += 1
                elif nums[si] > upper:
                    self.addRange(lower, upper)
                    break
                else:
                    self.addRange(lower, nums[si] - 1)
                    lower = nums[si] + 1
                    si += 1
            if lower <= upper:
                self.addRange(lower, upper)
            return self.results
    

Log in to reply
 

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