Iam_Sandeep

4. Median of Two Sorted Arrays

Jul 30th, 2022
968
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. class Solution:
  2.     def findMedianSortedArrays(self, A: List[int], B: List[int]) -> float:
  3.         if len(A)>len(B):
  4.             A,B=B,A
  5.         m,n=len(A),len(B)
  6.         tot=(m+n)
  7.         half = (m+n)>>1
  8.  
  9.         l,r=0,len(A)-1
  10.         while True:
  11.             c1=(l+r)>>1#c1--cut1 c2--cut2
  12.             c2=half-(c1+1)-1# making c1 to 1 indexed and than make c2 to 0 indexed
  13.             aleft=A[c1] if c1>=0 else float('-inf')#out of bounds
  14.             aright=A[c1+1] if c1+1<m else float('inf')
  15.             bleft=B[c2] if c2>=0 else float('-inf')
  16.             bright=B[c2+1] if c2+1<n else float('inf')
  17.             if aleft<=bright and bleft<=aright:
  18.                 if (tot)%2==1:
  19.                     return min(aright,bright)#verify with example [3] [2,4] remember not max(aleft,bleft) when total is odd
  20.                 else:
  21.                     return (max(aleft,bleft)+min(aright,bright))/2
  22.             elif aleft>bright:
  23.                 r=c1-1
  24.             else:
  25.                 l=c1+1
  26.  
  27.        
Advertisement
Add Comment
Please, Sign In to add comment