4. Median of Two Sorted Arrays

Problem

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)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

Related Topics:

Array Binary Search Divide and Conquer

Analysis

中位数:将一个集合分成等长的两部分,其中一部分总是小于另一部分。

我们可以将 AB 两个数组进行划分:

如果我们确保:

则可得到结果:

所以我们需要做的是:

通过二分查找,确定 i

加上边界值:

<b><c> 不需要判断 j,因为 i < m ==> j > 0i > 0 ==> j < n

Code

Last updated