看到这个题的第一思路就是用归并方法找到第(m+n)/2大的数,但是时间复杂度为O((m+n)/2)。
class Solution {
public:
double findMedianSortedArrays(vector<int> &A, vector<int> &B) {
int m = A.size();
int n = B.size();
int k = 0;
int i = 0; int j = 0;
int count = 0;
while (double(k) < double(m + n) / 2)
{
if (i >= m) { count = B[j]; j++; }
else if (j >= n) { count = A[i]; i++; }
else {
if (A[i] < B[j]) { count = A[i]; i++; }
else { count = B[j]; j++; }
}
k++;
}
if ((m + n )% 2 == 1) return count;
else
{
if (i >= m) return ((double)count / 2 + (double)B[j]/2);
if (i >= m) return ((double)count / 2 + (double)B[j] / 2);
if (j >= n) return ((double)count / 2 + (double)A[i] / 2);
if (A[i]<B[j]) return ((double)count / 2 + (double)A[i] / 2);
else return ((double)count / 2 + (double)B[j] / 2);
}
}
};
能达到O(log(m+n))时间复杂度的算法只能是分治。因为我们知道两个数组的长度分别为m和n,所以我们只需要找到第(m+n)/2大的数即可。通过分支,我们尝试在S1上找到一个割C1,同时得到S2上的一个割C2=(m+n)/2-C1,当C1左边的数L1小于C2右边的数R2,且C1右边的数R1大于C2左边的数L2的时候,说明C1和C2的位置切到了我们想要的位置上。这个算法的复杂度只有O(log(min{m,n}))。详细说明可以看这篇算法。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int m = nums2.size();
if(n > m) //保证数组1一定最短,加快查找速度
return findMedianSortedArrays(nums2,nums1);
int L1,L2,R1,R2,c1,c2,lo = 0, hi = 2*n; //我们目前是虚拟加了'#'所以数组1是2*n+1长度
while(lo <= hi) //二分
{
c1 = (lo+hi)/2; //c1是尝试在S1上二分的位置,这个位置是加了#的虚拟位置
c2 = m+n- c1;//由C1可以得到C2,也是虚拟位置
L1 = (c1 == 0)?INT_MIN:nums1[(c1-1)/2]; //S1所有都比中值大,中值从S2里找
R1 = (c1 == 2*n)?INT_MAX:nums1[c1/2]; //S1所有都比中值小,从S2找
L2 = (c2 == 0)?INT_MIN:nums2[(c2-1)/2];//S2所有都比中值大,从S1找
R2 = (c2 == 2*m)?INT_MAX:nums2[c2/2];//S2所有都比中值小,从S1找
if(L1 > R2) //S1里较大的值多,所以C1的位置应该靠前
hi = c1-1;
else if(L2 > R1)//S1里小的值多,所以C1的位置应该靠后
lo = c1+1;
else
break;
}
return (max(L1,L2)+ min(R1,R2))/2.0;
}
};