Python easy to understand solution


  • 0
    B

    Just add lower - 1 and upper + 1 to the nums, then check diff between two numbers to get the missing ranges

    class Solution(object):
        def findMissingRanges(self, nums, lower, upper):
            """
            :type nums: List[int]
            :type lower: int
            :type upper: int
            :rtype: List[str]
            """
            res = []
            
            if upper < lower:
                return res
            
            nums = [lower - 1] + [n for n in nums if n >= lower and n <= upper] + [upper + 1]
            
            for i in range(len(nums)-1):
                diff = nums[i + 1] - nums[i]
                if diff == 2:
                    ran = str(nums[i] + 1)
                    res.append(ran)
                if diff > 2:
                    ran = str(nums[i] + 1) + '->' + str(nums[i+1] - 1)
                    res.append(ran)
                    
            return res
    

Log in to reply
 

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