0004. Median of Two Sorted Arrays
Hard | Binary Search | 80 ms (97.98%), 14.5 MB (81.46%)
Last updated
Was this helpful?
Hard | Binary Search | 80 ms (97.98%), 14.5 MB (81.46%)
Last updated
Was this helpful?
Source: GitHub:
Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n))
.
At first, we find the total length of the merged array to understand how many elements are in the left and right parts respectively. size = (total_length + 1) // 2
Next, in each iteration, we take n
elements from nums1 and size - n
elements from nums2. l, r = 0, len(nums1)
n = (l + r) // 2
Then check whether selected elements are valid or not by comparing them with non-selected elements.
If valid, we return the median immediately. If not valid, we modify the search space.