Median of Two Sorted Arrays
HardBinary Search
You are given two arrays nums1 and nums2, each sorted in non-decreasing order (either one may be empty, but not both). Return the median of all m + n values taken together, as a float.
- If the total count is odd, the median is the middle value of the combined sorted order.
- If it is even, the median is the average of the two middle values.
The expected solution runs in O(log(m + n)) time; merging the arrays is O(m + n) and is the baseline to improve on. Answers within 10^-9 of the expected value are accepted.
Example 1
- Input:
- nums1 = [1,4,9], nums2 = [2,3,10,11]
- Output:
- 4.0
- Explanation
- Combined and sorted the values are 1, 2, 3, 4, 9, 10, 11. There are 7 of them, so the median is the 4th value, 4.
Example 2
- Input:
- nums1 = [-5,-3], nums2 = [-4,-1]
- Output:
- -3.5
- Explanation
- Combined the values are -5, -4, -3, -1. With an even count the median is the average of the two middle values, (-4 + -3) / 2 = -3.5.
Example 3
- Input:
- nums1 = [], nums2 = [2,3]
- Output:
- 2.5
- Explanation
nums1is empty, so the median comes fromnums2alone: the average of 2 and 3.
Constraints
0 <= nums1.length, nums2.length <= 10001 <= nums1.length + nums2.length <= 2000-10^6 <= nums1[i], nums2[i] <= 10^6- Both arrays are sorted in non-decreasing order