163. Missing Ranges

Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.

Example:

Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
Output: ["2", "4->49", "51->74", "76->99"]

Solution

(1) Java



(2) Python

class Solution:
    def findMissingRanges(self, nums, lower, upper):
        """
        :type nums: List[int]
        :type lower: int
        :type upper: int
        :rtype: List[str]
        """
        rst = []
        if not nums:
            if lower == upper:
                rst.append(str(lower))
            else:
                rst.append(str(lower)+"->"+str(upper))
            return rst
        start = lower
        for i in range(len(nums)):
            if nums[i] != start:
                if nums[i]-1 == start:
                    rst.append(str(start))
                elif start < nums[i]-1:
                    rst.append(str(start)+"->"+str(nums[i]-1))
            start = nums[i]+1
            if i == len(nums)-1:
                if start == upper:
                    rst.append(str(start))
                elif start < upper:
                    rst.append(str(start)+"->"+str(upper))
        return rst

(3) Scala



results matching ""

    No results matching ""