Missing Ranges

Problem: Missing Ranges

It's a quite simple solution. Just scan through the list to calculate the range. If range is small enough, use single number. If not, use arrows.

In my solution, I first deal with situation with empty list. Then I assign upper and lower into list so that I can better get boundary range.

Code in Python:

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

results matching ""

    No results matching ""