边工作边刷题:70天一遍leetcode: day 72

时间:2023-09-18 17:25:01

Missing Range

要点:题简单,这类题的特点都是记录上一步的状态,比如这题是end

错误点:

  • 三种情况:一是连续的,即和上一个end差1,而是中间只差1个数,没有’->',最后是大于1,有’->'
  • 看清题:upper/lower是boundary,不一定出现在nums里。为了统一,把upper+1放入nums,同时初始end=lower-1
  • 区间是[end+1, num-1]
  • 别忘了每次更新end

https://repl.it/Cjvy/2

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

# For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

# Hide Company Tags Google
# Hide Tags Array
# Hide Similar Problems (M) Summary Ranges class Solution(object):
def findMissingRanges(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: List[str]
"""
end = lower
res = []
for num in nums+[upper+1]:
if num!=end:
if num-1!=end:
res.append("{}->{}".format(end, num-1))
else:
res.append(str(num-1))
end = num+1 # error: don't forget return res sol = Solution()
assert sol.findMissingRanges([0, 1, 3, 50, 75], 0, 99)==['2', '4->49', '51->74', '76->99']