这题刚看时,确实没有认真对待,后来细做下来,一直没有比较高效的想法,无奈只好找大牛们的解答。后来看到这个http://blog.csdn.net/zxzxy1988/article/details/8587244才对这个问题清楚起来。代码如下:
//将题目转化为求第K小或大的题目,然后通过类似二分的方法求解
double findKth(int a[], int m, int b[], int n, int k)
{
//always assume that m is equal or smaller than n
if (m > n)
return findKth(b, n, a, m, k);
if (m == 0)
return b[k - 1];
if (k == 1)
return min(a[0], b[0]);
//divide k into two parts
int pa = min(k / 2, m), pb = k - pa;
if (a[pa - 1] < b[pb - 1])
return findKth(a + pa, m - pa, b, n, k - pa);
else if (a[pa - 1] > b[pb - 1])
return findKth(a, m, b + pb, n - pb, k - pb);
else
return a[pa - 1];
}
class Solution
{
public:
double findMedianSortedArrays(int A[], int m, int B[], int n)
{
int total = m + n;
if (total & 0x1)
return findKth(A, m, B, n, total / 2 + 1);
else
return (findKth(A, m, B, n, total / 2)
+ findKth(A, m, B, n, total / 2 + 1)) / 2;
}
};
double find_Kth(int A[],int m,int B[],int n,int K){
bool flaga=false,flagb=false;
//keep n>=m and assume A and B is ordered by inc
if(m>n)
return find_Kth(B, n, A, m, K);
if(m==0)return B[K-1];
if(K==1) return min(A[0],B[0]);
int pa=min(m,K/2),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];
if(A[0]>A[m-1])flaga=1;
if(B[0]>B[m-1])flagb=1;
//本来以为把以下4个情况都做,后来发现只用一种情况,故下面的代码基本没用
if(!flaga&&!flagb){
if((A[0]>=B[m-1])||(B[0]>=A[m-1])){
//if(m>n) return A[(m+n)/2-n];
return B[(m+n)/2-m];
}
}
if(!flaga&&flagb){
if((A[0]>=B[0])||(B[n-1]>=A[m-1])){
//if(m>n) return A[(m+n)/2-n];
return B[(m+n)/2-m];
}
}
if(flaga&&!flagb){
if((A[0]<=B[0])||(B[n-1]<=A[m-1])){
//if(m>n) return A[(m+n)/2-n];
return B[(m+n)/2-m];
}
}
if(flaga&&flagb){
if((A[0]<=B[m-1])||(B[0]<=A[m-1])){
//if(m>n) return A[(m+n)/2-n];
return B[(m+n)/2-m];
}
}
}