题目
题目链接
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.5f
解析
翻译了Solution
把数组A和数组B分别拆分成两边:
left_part | right_part |
---|---|
A[0], A[1], …, A[i-1] | A[i], A[i+1], …, A[m-1] |
B[0], B[1], …, B[j-1] | B[j], B[j+1], …, B[n-1] |
因为数组A有m个数,所以一共有m+1中分割的方法。
求中位数,即:
m+n是偶数时:
m+n是奇数时(把中位数放在左边):
即(先不考虑边界情况):
这很巧妙,j的表达式包括了m+n为奇数和偶数的两种情况。
&& B[j−1]≤A[i] and A[i−1]≤B[j] $$
当下,我们所需要做的就是令i从0遍历到m,以找到一个i使得$B[j−1]≤A[i]&&A[i−1]≤B[j]$,此时$j=(m+n+1)/2−i$
现在可以使用二分查找了。最开始的i的区间是[0, m],后来不断二分,缩小结果i所应当在的区间[imin, imax]。对每一轮新的循环,都令
i=(imin+imax)/2
和
j=(m+n+1)/2−i
。注意根据语言特性,i总是向下取整,因此中位数总是被包括在右边的数字集合中。我们将会遇到三种情况:
1. B[j−1]≤A[i] && A[i−1]≤B[j] —— 找到i,解决问题
2. B[j−1]>A[i] —— 增大i(即减小j),改变搜索区间为[imin = i+1, imax]
3. A[i−1]>B[j] —— 减小i,改变[imin,imax = i−1]
当找到i,最终结果即为:
m+n是偶数时:
m+n是奇数时(把中位数放在左边):
现在考虑边界情况: