40ms Python solution


  • 0
    W
    def findMissingRanges(self, nums, lower, upper):
        N = len(nums)
        if N==0:
            return [str(lower)+"->"+str(upper)] if upper>lower else [str(lower)]
    
        i = 0
        res=[]
       
        while i<N and lower<=upper: 
            while nums[i]<lower:
                i += 1
            diff = nums[i]-lower
            if diff==1:
                res.append(str(lower))
                lower = nums[i]+1
            elif diff>1:
                res.append(str(lower)+"->"+str(nums[i]-1)) 
                lower = nums[i]+1
            else: #nums[i]=lower
                lower += 1
          
            i += 1
          
        if i==N:
            diff = upper-nums[N-1]
            if diff==1:
                res.append(str(upper))
            elif diff>1:
                res.append(str(nums[N-1]+1)+"->"+str(upper))
    
    
        return res

Log in to reply
 

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