File tree 1 file changed +34
-0
lines changed
0004-median-of-two-sorted-arrays
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def findMedianSortedArrays (self , nums1 : List [int ], nums2 : List [int ]) -> float :
3
+ small , big = nums1 , nums2
4
+ total = len (nums1 ) + len (nums2 )
5
+ half = total // 2
6
+
7
+ if len (big ) < len (small ):
8
+ small , big = big , small
9
+
10
+ left , right = 0 , len (small ) - 1
11
+
12
+ while True :
13
+ # getting median index of both arrays
14
+ small_median = (left + right ) // 2
15
+ big_median = half - small_median - 2 # 2 is for balancing two zero indexes
16
+
17
+ small_left = small [small_median ] if small_median >= 0 else float ("-infinity" )
18
+ big_left = big [big_median ] if big_median >= 0 else float ("-infinity" )
19
+
20
+ small_right = small [small_median + 1 ] if (small_median + 1 ) < len (small ) else float ("infinity" )
21
+ big_right = big [big_median + 1 ] if (big_median + 1 ) < len (big ) else float ("infinity" )
22
+
23
+ # partiton is correct
24
+ if small_left <= big_right and big_left <= small_right :
25
+ # odd
26
+ if total % 2 :
27
+ return min (small_right , big_right )
28
+
29
+ # even
30
+ return (max (small_left , big_left ) + min (small_right , big_right )) / 2
31
+ elif small_left > big_right :
32
+ right = small_median - 1
33
+ else :
34
+ left = small_median + 1
You can’t perform that action at this time.
0 commit comments