美文网首页
Lintcode 65 Median of two Sorted

Lintcode 65 Median of two Sorted

作者: aha_zzb | 来源:发表于2018-05-16 16:11 被阅读0次

AC

//Description :There are two sorted arrays A and B of size m and n respectively.Find the median of the two sorted arrays.
//Challenge: The overall run time complexity should be O(log(m + n)).
//part of q532, how to find values in two sorted arrays

    /*
     * @param A: An integer array
     * @param B: An integer array
     * @return: a double whose format is *.5 or *.0
     */
    double findMedianSortedArrays(vector<int> &A, vector<int> &B) {
        // write your code here
        int i = A.size(), j = B.size();
        vector<int> temp(i+j);
        int m=0,n=0,t=0;
        while (m<i && n<j) {
            if (A[m]>B[n]) temp[t++]=B[n++];
            else temp[t++]=A[m++];
        }
        while (m<i) temp[t++]=A[m++];
        while (n<j) temp[t++]=B[n++];
        double med;
        int index = (i+j)/2;
        if ((i+j)%2==0) return (temp[index]+temp[index-1])/2.0;
        else return temp[index];
    }

相关文章

网友评论

      本文标题:Lintcode 65 Median of two Sorted

      本文链接:https://www.haomeiwen.com/subject/dbapdftx.html