题目:
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)).
题目大意:给定两个已经排序的数组,计算它们的中值。
解题思路:这道题有复杂度的要求,而我没什么太好的思路,借鉴了其他人的做法,比较经典的是计算第kth个数来求解,主要思路,采用二分的策略,将查找联合数组的kth转换为求解两个子数组的第kth/2的问题。
利用这样一个事实:
当A[k/2-1] == B[k/2-1],找到kth的数直接返回
当A[k/2-1] < B[k/2-1],则数组A的前[k/2-1]个数必定在联合数组kth个数的左侧(因为子数组成升序排列),递增A的下标。
当A[k/2-1] >B[k/2-1],同上。
具体还需要注意三个边界条件:
1.m > n 则重新调用函数使得保证m<n。
2.m == 0,即A数组为空,直接返回B[k-1]。
3.k == 1,直接返回min(A[0],B[0])。
代码如下:
public:
// Other person's method
int getKth(int A[], int m, int B[], int n, int k){
if(m == 0)
return B[k-1];
if(m > n)
return getKth(B, n, A, m, k);
if( k == 1){
return A[0] < B[0] ? A[0] : B[0];
}
int pa = k / 2 > m ? m : k / 2 ;
int pb = k - pa ;
// If A[pa-1] < B[pb-1], then the kth number must not in the A[1...pa-1], change the A's index, reverse is also true.
if(A[pa - 1] < B[pb - 1])
return getKth(A+pa, m-pa, B, n, k-pa);
else if(A[pa-1] > B[pb-1])
return getKth(A, m, B+pb, n-pb, k-pb);
else
// if equal return.
return A[pa-1];
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if((m+n) % 2)
return getKth(A, m, B, n, (m+n)/2+1);
else{
return (getKth(A, m, B, n, (m+n)/2) + getKth(A, m, B, n, (m+n)/2+1))/2.0;
}
}
};