4. Median of Two Sorted Arrays
There are two sorted arrays nums1and 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)).
Example 1:
Example 2:
Thoughts:
use binary search to find the best partition i and j in nums1 and nums2 such that nums1[i] > nums 2[j -1] && nums2[j] > nums1[i -1]. Also j = (m + n +1 )/ 2 - j (for n as the "longer" array length and m as the "shorter" array length, m >= n) to guarantee that i + j is the median position for odd number total length and left input of computing median for even total length.
Code Time Complexity: O(min(m,n)), Space Complexity: O(1)
Special Thanks to missmary's solution& explanation and jianchao.li.fighter's code
Last updated
Was this helpful?