题目:
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)).
解析:求两个排序数组的中位数,数组长度分别是m和n,要求时间复杂度为O(log(m+n))。刚开始思路是利用类似合并排序的思路分别遍历两个数组,但是算法复杂度为O(n)。
查看网上的解题方法,原问题其实是一个寻找第k小数的问题,中位数实际上是第(m+n)/2小的数。对于数组a和b,比较A的第k/2小的元素A[k/2-1]和B的第k/2小的元素B[k/2-1]两个元素,有三种情况可以考虑:
1. A[k/2-1]<B[k/2-1]表示A[0]到A[k/2-1]的元素都在A和B合并之后的前k小的元素中,可以把A[0]到A[k/2-1]的元素抛弃
2. A[k/2-1]>B[k/2-1]表示B[0]到B[k/2-1]的元素都在A和B合并之后的前k小的元素中,可以把B[0]到B[k/2-1]的元素抛弃
3. A[k/2-1]=B[k/2-1]表示A[k/2-1]即为第k小的元素
Java AC代码:
public class Solution{
public double findMedianSortedArrays(int A[], int B[]) {
double temp = findK(A, 0, B, 0, (A.length + B.length) / 2 + 1);
if ((A.length + B.length) % 2 == 0) {
temp = (temp + findK(A, 0, B, 0, (A.length + B.length) / 2)) / 2;
}
return temp;
}
public double findK(int[] A, int aLeft, int[] B, int bLeft, int k) {
if (A.length - aLeft < B.length - bLeft) {
return findK(B, bLeft, A, aLeft, k);
} else if (bLeft >= B.length) {
return A[k - 1];
} else if (k == 1) {
return Math.min(A[aLeft], B[bLeft]);
}
int pb = Math.min(k / 2, B.length - bLeft);
int pa = k - pb;
if (A[aLeft + pa - 1] > B[bLeft + pb - 1]) {
return findK(A, aLeft, B, bLeft + pb, k - pb);
} else if (A[aLeft + pa - 1] < B[bLeft + pb - 1]) {
return findK(A, aLeft + pa, B, bLeft, k - pa);
} else {
return A[pa - 1];
}
}
}