## LeetCode: Median of Two Sorted Arrays

https://leetcode.com/problems/median-of-two-sorted-arrays/solution/

http://www.cnblogs.com/yuzhangcmu/p/4138184.html

http://blog.csdn.net/gao1440156051/article/details/51725845

http://blog.csdn.net/linhuanmars/article/details/19905515

class Solution {
public:

double findMedianSortedArrays(int A[], int m, int B[], int n) {
int size = m + n;
if (size & 0x1){
return findKth(A,m,B,n,size/2+1);
}else{
double a = findKth(A,m,B,n,size/2);
double b = findKth(A,m,B,n,size/2+1);
//cout<<a<<" "<<b<<endl;
return (a + b)/2;
}
//return mergeSort(A,m,B,n);
}

double findKth(int A[], int m, int B[],int n, int k){
if (m > n){
return findKth(B,n,A,m,k);
}
if (0 == m){
return B[k-1];
}
if (1 == k){
return min(A[0],B[0]);
}
int pa = min(m,k/2);
int 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];
}
}
};


posted on 2017-09-02 19:44  月下之风  阅读(145)  评论(0编辑  收藏  举报