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:
int findKth(int A[], int m, int B[], int n, int k) {
int l = k - 1 - std::min(k - 1, n), r = std::min(k, m);
while (l <= r) {
int i = l + ((r - l) >> 1);
int j = k - 1 - i;
if (i >= 0 && i < m && (j >= n || A[i] <= B[j]) && (j == 0 || B[j-1] <= A[i]))
return A[i];
else if (j >= 0 && j < n && (i >= m || B[j] <= A[i]) && (i == 0 || A[i-1] <= B[j]))
return B[j];
if (j >= n || A[i] < B[j]) l = i + 1;
else r = i - 1;
}
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if ((m + n) & 1) return findKth(A, m, B, n, ((m + n) >> 1) + 1);
else return (findKth(A, m, B, n, (m + n) >> 1) + findKth(A, m, B, n, ((m + n) >> 1) + 1)) * 0.5;
}
};