There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
1 | nums1 = [1, 3] |
Example 2:
1 | nums1 = [1, 2] |
Analyzation:
Median will divide the array into two parts with equal length.
Given len(A) = m, len(B) = n
, if we have:
1 | left | right |
1 | A[0],A[1]...A[i - 1] | A[i], A[i + 1] ... A[m - 1] |
1 | B[0],B[1]...B[j - 1] | B[j], B[j + 1] ... B[n - 1] |
And
1 | For A and B, len(left) == len(right); |
We can get median = (max(A[i - 1], B[j - 1]) + max(A[i] + B[j])) / 2
;
Ps: Need to keep m <= n
since j = (m + n) / 2 - i
and 0 < i < m
. When m > n
, j
will be negative.
So our objective is to find
1 | left | right |