Given two sorted arrays nums1 and nums2 of size m and n, return the median of the two sorted arrays. The overall run time complexity must be O(log(m+n)).
nums1 = [1,3], nums2 = [2]2.0nums1 = [1,2], nums2 = [3,4]2.5lo=0, hi=mi = (lo+hi)/2, derive j = (m+n+1)/2 − imaxL1, minR1, maxL2, minR2 (use ±∞ at edges)maxL1 > minR2: i too large → hi = i−1maxL2 > minR1: i too small → lo = i+1We binary-search on partition index i in the shorter array A.
For any i, we know exactly how many elements go into the left half from B:
j = ⌊(m+n+1)/2⌋ − i.
The partition is valid when
maxL1 ≤ minR2 and maxL2 ≤ minR1 —
meaning the combined left side truly contains the ⌊(m+n)/2⌋ smallest elements.
For odd total: median = max(maxL1, maxL2).
For even total: median = (max(maxL1,maxL2) + min(minR1,minR2)) / 2.