LeetCode OJ--Median of Two Sorted Arrays ***

http://oj.leetcode.com/problems/median-of-two-sorted-arrays/

找两个有序数组的中位数,因为有序数组,并且复杂度要求O(lg(m+n))所以想到了使用二分,但具体怎么做,没分析清楚。

参考了网上http://blog.csdn.net/zxzxy1988/article/details/8587244 ,其他的类似找两个有序数组中第 k 大的也可以这样处理。

#include <iostream>
using namespace std;

double findKth(int a[],int m,int b[],int n,int k)
{
    if(m>n) //总是让a中个数小于b中个数
        return findKth(b,n,a,m,k);
    if(m == 0) //一个数组为空了,只需要在b中求第k个
        return b[k-1];
    if(k == 1) //就差一个数了
        return min(a[0],b[0]);
    int pa = min(k/2,m), pb = k - pa;  //好写法
    if(a[pa - 1]<b[pb-1]) //a中的pa个可以都算进来了
        return findKth(a+pa,m-pa,b,n,k-pa); //a+pa,m-pa来表示,good
    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;
    }
};

int main()
{
    int A[] = {1,4,6,7,9};
    int B[] = {3,5,6,8};
    Solution *myS = new Solution();
    double ans = myS->findMedianSortedArrays(A,5,B,4);
    cout<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/qingcheng/p/3516552.html