[Cpp]
Class Solution {
// More detail refer to: http://fisherlei.blogspot.com/2012/12/leetcode-median-of-two-sorted-arrays.html
// Using the method of getting the kth number in the two sorted array to solve the median problem
// Divide-and-conquer
// Very clean and concise
Public:
Double findMedianSortedArrays (int A [], int m, int B [], int n ){
If (n + m) % 2 = 0)
{
Return (GetMedian (A, m, B, n, (m + n)/2) + GetMedian (A, m, B, n, (m + n) /2 + 1)/2.0;
}
Else
Return GetMedian (A, m, B, n, (m + n)/2 + 1 );
}
Int GetMedian (int a [], int n, int B [], int m, int k) // get the kth number in the two sorted array
{
// Assert (a & B );
If (n <= 0) return B [k-1];
If (m <= 0) return a [k-1];
If (k <= 1) return min (a [0], B [0]);
// A: section1 section2
// B: section3 section4
If (B [m/2]> = a [n/2])
{
If (n/2 + 1 + m/2)> = k)
Return GetMedian (a, n, B, m/2, k); // abort section 4
Else
Return GetMedian (a + n/2 + 1, n-(n/2 + 1), B, m, k-(n/2 + 1 )); // abort section 1
}
Else
{
If (m/2 + 1 + n/2)> = k)
Return GetMedian (a, n/2, B, m, k); // abort section 2
Else
Return GetMedian (a, n, B + m/2 + 1, m-(m/2 + 1), k-(m/2 + 1 )); // abort section 3
}
}
};