class Solution {
/**
* @param A: An integer array.
* @param B: An integer array.
* @return: a double whose format is *.5 or *.0
*/
public double findMedianSortedArrays(int[] A, int[] B) {
// write your code here
int length = A.length + B.length;
if (length % 2 == 0) {
return (find(length / 2, A, 0, B, 0) + find (length / 2 + 1, A, 0, B, 0)) / 2.0;
} else {
return find(length / 2 + 1, A, 0, B, 0);
}
}
double find(int k, int[] A, int astart, int[] B, int bstart) {
if (astart >= A.length) {
return B[bstart + k - 1];
}
if (bstart >= B.length) {
return A[astart + k - 1];
}
if (k == 1) {
return Math.min(A[astart], B[bstart]);
}
int akey = astart + k / 2 - 1 < A.length
? A[astart + k / 2 - 1]
: Integer.MAX_VALUE;
int bkey = bstart + k / 2 - 1 < B.length
? B[bstart + k / 2 - 1]
: Integer.MAX_VALUE;
if (akey < bkey) {
return find(k - k / 2, A, astart + k / 2, B, bstart);
} else {
return find(k - k / 2, A, astart, B, bstart + k / 2);
}
}
}
Problems: find the median of two sorted arrays A, B.
Prototype problem: find the K-th largest elements of two sorted arrays A, B.
Challenges:
(1) If A.length + B.length is even, the median is the average of the middle two elements.
If its odd, the median is the very element in the middle
(2) If we run out of A or B, then the K-th largest element is theOtherArray[k-1]. 2 EDGE CASES HERE
(3) neither A nor B is run out of, we need to find the K / 2 -th largest element in the two arrays.
The K / 2 -th largest element of a single array is actually in the index of [K / 2 - 1]. Since we divided K by two, K == 1 is an EDGE CASE.
(4) How do you throw away ~ K / 4 elements every time?
If(akey) < (bkey) then throw away A[astart ... K / 2 - 1]