[LintCode] Median of Two Sorted Arrays 两个有序数组的中位数

时间:2021-09-27 01:46:46

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays.

Have you met this question in a real interview?
 
 
Example

Given A=[1,2,3,4,5,6] and B=[2,3,4,5], the median is 3.5.

Given A=[1,2,3] and B=[4,5], the median is 3.

Challenge

The overall run time complexity should be O(log (m+n)).

LeetCode上的原题,请参见我之前的博客Median of Two Sorted Arrays

解法一:

class Solution {
public:
/**
* @param A: An integer array.
* @param B: An integer array.
* @return: a double whose format is *.5 or *.0
*/
double findMedianSortedArrays(vector<int> A, vector<int> B) {
int n1 = A.size(), n2 = B.size();
if (n1 < n2) return findMedianSortedArrays(B, A);
if (n2 == ) return ((double)A[(n1 - ) / ] + (double)A[n1 / ]) / ;
int left = , right = n2 * ;
while (left <= right) {
int mid2 = (left + right) / ;
int mid1 = n1 + n2 - mid2;
double L1 = mid1 == ? INT_MIN : A[(mid1 - ) / ];
double L2 = mid2 == ? INT_MIN : B[(mid2 - ) / ];
double R1 = mid1 == n1 * ? INT_MAX : A[mid1 / ];
double R2 = mid2 == n2 * ? INT_MAX : B[mid2 / ];
if (L1 > R2) left = mid2 + ;
else if (L2 > R1) right = mid2 - ;
else return (max(L1, L2) + min(R1, R2)) / ;
}
return -;
}
};

解法二:

class Solution {
public:
/**
* @param A: An integer array.
* @param B: An integer array.
* @return: a double whose format is *.5 or *.0
*/
double findMedianSortedArrays(vector<int> A, vector<int> B) {
int m = A.size(), n = B.size(), left = (m + n + ) / , right = (m + n + ) / ;
return (findKth(A, B, left) + findKth(A, B, right)) / 2.0;
}
double findKth(vector<int> A, vector<int> B, int k) {
int m = A.size(), n = B.size();
if (m > n) return findKth(B, A, k);
if (m == ) return B[k - ];
if (k == ) return min(A[], B[]);
int i = min(m, k / ), j = min(n, k / );
if (A[i - ] > B[j - ]) {
return findKth(A, vector<int>(B.begin() + j, B.end()), k - j);
} else {
return findKth(vector<int>(A.begin() + i, A.end()), B, k - i);
}
return -;
}
};