There are two sorted arrays A and B 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)).
解决方法(C++版):
class Solution {
public:
double findMedianSortedArrays(int A [], int m, int B [], int n) {
int temp = m + n;
if (temp & 0x1){
return findMaxNumber(A,m,B,n,temp/2+1);
}
else{
return (findMaxNumber(A, m, B, n, temp / 2) + findMaxNumber(A, m, B, n, temp / 2 + 1))/2.0;
}
}
double findMaxNumber(int A [], int m, int B [], int n,int k){
if (m > n)
return findMaxNumber(B, n, A, m, k);
if (0 == m)
return B [k-1];
if (1 == k)
return A[0] > B[0] ? B[0] : A[0];
int atemp = m < k / 2 ? m : k / 2;
int btemp = k - atemp;
if (A[atemp-1] < B[btemp-1])
return findMaxNumber(A + atemp, m - atemp, B, n, k - atemp);
else if (A[atemp-1] > B[btemp-1])
return findMaxNumber(A, m, B + btemp, n - btemp, k - btemp);
else
return A[atemp-1];
}
};