原题:
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解题方法:
题目要求log(N)的时间复杂度,需要用类二分查找的算法,可以称之为二分切割法,将两个数组分别切成左右两部分,左右两部分的数的个数相等,而且左边的数一定小于右边的数。最后(左边大数+右边小数)/2.0就是最终的答案。
代码:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n1 = nums1.size(), n2 = nums2.size();
// 确保n1 <= n2
if (n1 > n2)
return findMedianSortedArrays(nums2, nums1);
int L1 = 0, R1 = 0, L2 = 0, R2 = 0, C1 = 0, C2 = 0, lo = 0, hi = 2 * n1;
// 用二分切割法两个数组分别切成左右两部分,最后左边部分的数都小于右边部分的数。
while (lo <= hi){
C1 = lo + ( (hi - lo) >> 1);
C2 = n1 + n2 - C1;
// 如果C1是奇数,L1 = R1
L1 = (C1 < 1) ? INT_MIN : nums1[(C1-1)/2];
R1 = (C1 == 2*n1) ? INT_MAX : nums1[C1/2];
// 如果C2是奇数,L2 = R2
L2 = (C2 < 1) ? INT_MIN : nums2[(C2-1)/2];
R2 = (C2 == 2*n2) ? INT_MAX : nums2[C2/2];
if (L1 > R2)
hi = C1 - 1;
else if (R1 < L2)
lo = C1 + 1;
else
break;
}
// 取出左边部分较大的数和右边部分较小的数,两者之和除以2就是所求答案。
return ( max(L1, L2) + min(R1, R2) )/2.0;
}