LeetCode 4. Median of Two Sorted Arrays
Question
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))
.
Example 1:
1 | Input: nums1 = [1,3], nums2 = [2] |
Example 2:
1 | Input: nums1 = [1,2], nums2 = [3,4] |
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
Source: https://leetcode.com/problems/median-of-two-sorted-arrays/
Solution
A simple solution is to maintain two pointers for two sorted arrays, and use linear search to find the median. Obviously, it is simple but slow.
Because both arrays are sorted, we can use binary search to improve performance. Remember that the essence of binary search is to exclude a certain percentage of candiates from the search range on each round.
1 | // Time complexity: O(log(m+n)), because k = (m+n)/2 |
LeetCode 4. Median of Two Sorted Arrays
http://yenotes.org/2022/03/11/LeetCode-4-Median-of-Two-Sorted-Arrays/