lance6716

Untitled

Jun 25th, 2019
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. class Solution:
  2.     def lengthOfLIS(self, nums: List[int]) -> int:
  3.         # we scan the nums left to right,
  4.         # use `end[i]` to record 'what is the minimum ending number of length `i`',
  5.         #
  6.         # how to maintenance `end`:
  7.         # while scanning, updating the current number to accroding position of `end`
  8.         # if end[i] < cur: end[i + 1] = min(end[i + 1], cur)
  9.         # but i + 1 will overflow, so append when overflow
  10.         #
  11.         # python array is 0-based, above index of end will minus 1
  12.        
  13.         end = []
  14.         for cur in nums:
  15.             # find right-most i s.t. end[i] < cur
  16.             # return -1 if no one
  17.             i = self.find(end, cur)
  18.             if i == len(end) - 1:
  19.                 end.append(cur)
  20.             else:
  21.                 end[i + 1] = min(end[i + 1], cur)
  22.         return len(end)
  23.    
  24.     def find(self, arr, target):
  25.         # find right-most i s.t. end[i] < cur
  26.         # return -1 if no one
  27.         # invariant: left <= ret <= right
  28.        
  29.         left, right = -1, len(arr) - 1
  30.         while left < right:
  31.            
  32.             # 2.5 rounding to 2 or 3?
  33.             # should check when left + 1 == right and the if-statement won't result in a deadloop
  34.             # when left + 1 == right, mid here will be right, both branch shrink
  35.            
  36.             # here left is initiated -1 which is not in a legal range, carefully think of underflow
  37.             # when underflow, left and right must be both -1, so wo could return here
  38.             mid = (left + right + 1) // 2
  39.             if mid == -1:
  40.                 return -1
  41.             if arr[mid] < target:
  42.                 left = mid # ans in [mid, right]
  43.             else:
  44.                 right = mid - 1 # and in [left, mid - 1]
  45.            
  46.         return left
Add Comment
Please, Sign In to add comment