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)).
同时遍历两个数组,取小的直到中间数。
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int i = 0, j = 0;
double pre,result;
while((i+j) <= ((m + n) / 2)){
pre = result;
if(i >= m){ //A数组取完
result = B[j];
j++;
}
else if(j >= n){ //B数组取完
result = A[i];
i++;
}
else if(A[i] > B[j]){
result = B[j];
j++;
}
else{
result = A[i];
i++;
}
}
if((m + n) % 2){
return result;
}
else{
return (pre + result) / 2.0;
}
}
};
利用二分查找寻找第(m+n)/2+1小的数字
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if((m + n) % 2 == 1){
return findMid(A, m, B, n,(m+n) / 2 + 1);
}
else{
return (findMid(A, m, B, n, (m + n) / 2) + findMid(A, m, B, n, (m + n) / 2 + 1)) / 2.0;
}
}
double findMid(int a[],int m, int b[], int n, int k){
if(m > n){ //m<=n
return findMid(b, n, a, m, k);
}
if(m == 0){
return b[k - 1];
}
if(k == 1){
return min(a[0],b[0]);
}
int aMid = min(k / 2, m);
int bMid = k - aMid;
if(a[aMid - 1] < b[bMid - 1]){
return findMid(a + aMid, m - aMid, b, n, k - aMid);
}
else if(a[aMid - 1] > b[bMid - 1]){
return findMid(a, m, b + bMid, n - bMid, k - bMid);
}
else{
return a[aMid - 1];
}
}
};