Advertisement
TwentyEight

1n73r\/4L

May 24th, 2020
1,561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. class Solution:
  2.     def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
  3.         ans = []
  4.         i, j = 0, 0 # look at two intervals at a time, A[i] and B[j]
  5.         while i < len(A) and j < len(B):
  6.             # find bounds of intersection (if two intervals intersect)
  7.             lower = max(A[i][0], B[j][0])
  8.             higher = min(A[i][1], B[j][1])
  9.            
  10.             if lower <= higher:
  11.                 # is an intersection; add to answer
  12.                 ans += [[lower, higher]]
  13.                
  14.             # now look at a different pair of intervals
  15.             if A[i][1] < B[j][1]: # A[i] ended before B[j]
  16.                 i += 1
  17.             elif A[i][1] > B[j][1]: # B[j] ended before A[i]
  18.                 j += 1
  19.             else: # note if both intervals end at the same time, both i and j increments
  20.                 i += 1
  21.                 j += 1
  22.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement