Description:
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
Example
Example 1
Input:
nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99
Output:
["2", "4->49", "51->74", "76->99"]
Explanation:
in range[0,99],the missing range includes:range[2,2],range[4,49],range[51,74] and range[76,99]
Example 2
Input:
nums = [0, 1, 2, 3, 7], lower = 0 and upper = 7
Output:
["4->6"]
Explanation:
in range[0,7],the missing range include range[4,6]
Solution: 很无聊的一道题,各种corner cases
NTOE: 刚开始只是把lower和upper+1输入到nums里,后来评论区提醒,要把lower-1替换lower
class Solution:
"""
@param: nums: a sorted integer array
@param: lower: An integer
@param: upper: An integer
@return: a list of its missing ranges
"""
def findMissingRanges(self, nums, lower, upper):
# write your code here
def helper(l,h):
if l == h:
return str(l)
else:
return str(l) + "->" + str(h)
if not nums:
return [helper(lower,upper)]
nums = [lower-1] + nums + [upper+1]
ret = []
for i in range(1,len(nums)):
n1,n2 = nums[i-1],nums[i]
if n2 > n1+1:
ret.append(helper(n1+1,n2-1))
if not ret:
if lower == nums[1]:
return []
else:
return [helper(lower,nums[1])]
else:
return ret