public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
int sumOfLen = A.length + B.length;
return sumOfLen % 2 == 1
? recFindK(A, B, 0, A.length - 1, 0, B.length - 1, sumOfLen / 2 + 1)
: (recFindK(A, B, 0, A.length - 1, 0, B.length - 1, sumOfLen / 2)
+ recFindK(A, B, 0, A.length - 1, 0, B.length - 1, sumOfLen / 2 + 1)) / 2;
}
// kth element of the merged (cut) arrays
// lowX, highX are all inclusive
// By default, the effective size of array A is not greater than array B
private double recFindK(int A[], int B[], int lowA, int highA, int lowB, int highB, int k) {
// Base cases
if(highA - lowA > highB - lowB) {
return recFindK(B, A, lowB, highB, lowA, highA, k);
}
if(lowA == highA + 1) {
return B[lowB + k - 1];
}
if(k == 1) {
return Math.min(A[lowA], B[lowB]);
}
// Recursion
int a = Math.min(k / 2, highA - lowA + 1), b = k - a;
if(A[lowA + a - 1] == B[lowB + b - 1]) {
return A[lowA + a - 1];
} else if(A[lowA + a - 1] < B[lowB + b - 1]) {
return recFindK(A, B, lowA + a, highA, lowB, highB, k - a);
} else {
return recFindK(A, B, lowA, highA, lowB + b, highB, k - b);
}
}
}
Time: O(log(m + n))
Space: O(log(m + n))