您的位置:首页 > 其它

LeetCode: Median of Two Sorted Arrays

2017-09-02 19:44 369 查看
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];
}
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: