10 lines of python beats 99%


  • 0
    Y

    We just have to examine current val and prev val, if current val is larger than prev val for more than 1, then we got an output to add to ret array.

    To handle edge conditions, add both ends of the nums array with a sentinel number, lower-1 for left and upper+1 for right, then you don't need a lot of if statements.

    class Solution:
        def findMissingRanges(self, nums, lower, upper):
            """
            :type nums: List[int]
            :type lower: int
            :type upper: int
            :rtype: List[str]
            """
            ret = []
            nums = [lower-1] + nums + [upper+1]
            n = len(nums)
            for i in range(1, n):
                val = nums[i]
                prev = nums[i-1]
                if val - prev > 1:
                    low = prev+1
                    high = val-1
                    if low == high: ret.append(str(low))
                    else: ret.append("{}->{}".format(low, high))
            return ret
    

Log in to reply
 

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