jinhuang1102

163. Missing Ranges

Feb 19th, 2019
1,262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. """
  2. 163. Missing Ranges
  3. 这道题自己做逻辑做乱了的一道题。然后这是别人的想法我觉得很清晰:
  4. Check each num in nums[]. Initialize another variable next = lower.
  5.  
  6. If nums[i]< next: we jump to next num to check if it’s in range.
  7. If nums[i]== next: it means we find the first num in range. We increment the next target by one.
  8. If nums[i] > next: Add the missing range [next, nums[i] — 1]. Update the next value to nums[i] + 1.
  9. 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.
  10. We create a separate function getRange(int unm1, int num2) to deal with two cases: num1 == num2 or num1 < num2
  11.  
  12. """
  13.  
  14. class Solution(object):
  15.     def findMissingRanges(self, nums, lower, upper):
  16.         """
  17.        :type nums: List[int]
  18.        :type lower: int
  19.        :type upper: int
  20.        :rtype: List[str]
  21.        """
  22.         res = []
  23.         next_lower = lower
  24.        
  25.         for i in range(0, len(nums)):
  26.             if nums[i] < next_lower:
  27.                 continue
  28.             elif nums[i] == next_lower:
  29.                 next_lower += 1
  30.                 continue
  31.             else:
  32.                 if next_lower == nums[i]-1:
  33.                     tmp = str(next_lower)
  34.                 else:
  35.                     tmp = str(next_lower) + "->" + str(nums[i]-1)
  36.                    
  37.                 res.append(tmp)
  38.                 next_lower = nums[i]+1
  39.        
  40.         if next_lower < upper:
  41.             tmp = str(next_lower) + "->" + str(upper)
  42.             res.append(tmp)
  43.         elif next_lower == upper:
  44.             tmp = str(next_lower)
  45.             res.append(tmp)
  46.            
  47.        
  48.         return res
Advertisement
Add Comment
Please, Sign In to add comment