# LeetCode 4 — Median of Two Sorted Arrays （C++ Java Python）

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)).

由于要求时间复杂度为O(log (m+n))，可参考二分查找的思想，先考虑一般情况，即查找第k大的数。

C++实现：

class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int total = m + n;
if(total & 0x01)
{
return find_kth(A, m, B, n, total / 2 + 1);
}
else
{
return (find_kth(A, m, B, n, total / 2) +
find_kth(A, m, B, n, total / 2 + 1)) / 2.0;
}
}

double find_kth(int A[], int m, int B[], int n, int k)
{
if(m > n)
{
return find_kth(B, n, A, m, k);
}
if(m == 0)
{
return B[k - 1];
}
if(k == 1)
{
return std::min(A[0], B[0]);
}

int pa = std::min(k / 2, m);
int pb = k - pa;
if(A[pa - 1] < B[pb - 1])
{
return find_kth(A + pa, m - pa, B, n, k - pa);
}
else if(A[pa - 1] > B[pb - 1])
{
return find_kth(A, m, B + pb, n - pb, k - pb);
}
else
{
return A[pa - 1];
}
}
};

Java实现：

public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int m = A.length;
int n = B.length;
int total = m + n;
if ((total & 0x01) != 0) {
return find_kth(A, m, B, n, total / 2 + 1);
} else {
return (find_kth(A, m, B, n, total / 2) + find_kth(A, m, B, n,
total / 2 + 1)) / 2.0;
}
}

public double find_kth(int A[], int m, int B[], int n, int k) {
if (m > n) {
return find_kth(B, n, A, m, k);
}
if (m == 0) {
return B[k - 1];
}
if (k == 1) {
return Math.min(A[0], B[0]);
}

int pa = Math.min(k / 2, m);
int pb = k - pa;
if (A[pa - 1] < B[pb - 1]) {
return find_kth(Arrays.copyOfRange(A, pa, A.length), m - pa, B, n,
k - pa);
} else if (A[pa - 1] > B[pb - 1]) {
return find_kth(A, m, Arrays.copyOfRange(B, pb, B.length), n - pb,
k - pb);
} else {
return A[pa - 1];
}
}

public static void main(String[] args) {
int[] A = { 1, 3 };
int[] B = { 2, 4 };
Solution slt = new Solution();
double result = slt.findMedianSortedArrays(A, B);
System.out.println(result);
}
}

Python实现：

class Solution:
# @return a float
def findMedianSortedArrays(self, A, B):
m = len(A)
n = len(B)
total = m + n
if total & 0x01:
return self.find_kth(A, m, B, n, total / 2 + 1)
else:
return (self.find_kth(A, m, B, n, total / 2) +
self.find_kth(A, m, B, n, total / 2 + 1)) / 2.0

def find_kth(self, A, m, B, n, k):
if m > n:
return self.find_kth(B, n, A, m, k)
if m == 0:
return B[k - 1]
if k == 1:
return min(A[0], B[0])

pa = min(k / 2, m)
pb = k - pa
if A[pa - 1] < B[pb - 1]:
return self.find_kth(A[pa:], m - pa, B, n, k - pa)
elif A[pa - 1] > B[pb - 1]:
return self.find_kth(A, m, B[pb:], n - pb, k - pb)
else:
return A[pa - 1]

感谢阅读，欢迎评论！