Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- 163. Missing Ranges
- 这道题自己做逻辑做乱了的一道题。然后这是别人的想法我觉得很清晰:
- Check each num in nums[]. Initialize another variable next = lower.
- If nums[i]< next: we jump to next num to check if it’s in range.
- If nums[i]== next: it means we find the first num in range. We increment the next target by one.
- If nums[i] > next: Add the missing range [next, nums[i] — 1]. Update the next value to nums[i] + 1.
- After we finished the above loop, we need to double check the final next value. If next ≤ upper, we still have a missing range [next, upper] to add.
- We create a separate function getRange(int unm1, int num2) to deal with two cases: num1 == num2 or num1 < num2
- """
- class Solution(object):
- def findMissingRanges(self, nums, lower, upper):
- """
- :type nums: List[int]
- :type lower: int
- :type upper: int
- :rtype: List[str]
- """
- res = []
- next_lower = lower
- for i in range(0, len(nums)):
- if nums[i] < next_lower:
- continue
- elif nums[i] == next_lower:
- next_lower += 1
- continue
- else:
- if next_lower == nums[i]-1:
- tmp = str(next_lower)
- else:
- tmp = str(next_lower) + "->" + str(nums[i]-1)
- res.append(tmp)
- next_lower = nums[i]+1
- if next_lower < upper:
- tmp = str(next_lower) + "->" + str(upper)
- res.append(tmp)
- elif next_lower == upper:
- tmp = str(next_lower)
- res.append(tmp)
- return res
Advertisement
Add Comment
Please, Sign In to add comment