码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Median of Two Sorted Arrays

时间:2014-11-11 12:45:34      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

题目描述:

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).


思路:写一个找两个数组中第k大数的函数,每次至少可以在数组A或数组B中排除min(m,n,k/2)个元素。递归调用该函数,直到k=1或者A、B中一个元素为空。


代码:

double Solution::findMedianSortedArrays(int A[], int m, int B[], int n)
{
    return (find_Kth(A,m,B,n,(m+n+1)/2) + find_Kth(A,m,B,n,(m+n+2)/2)) / 2.0;
}

int Solution::find_Kth(int A[],int m,int B[],int n,int k)
{
    if(m == 0)
        return B[k-1];
    if(n == 0)
        return A[k-1];
    if(k == 1)
        return min(A[0],B[0]);

    int i = min(m,k/2);
    int j = min(n,k/2);

    if(A[i-1] > B[j-1])
        return find_Kth(A,m,B+j,n-j,k-j);
    else
        return find_Kth(A+i,m-i,B,n,k-i);
}


LeetCode:Median of Two Sorted Arrays

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/41008473

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!