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

Median of Two Sorted Arrays

时间:2014-10-08 14:00:15      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   ar   java   sp   div   c   on   

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)).

答案

public class Solution {
    public double findMedianSortedArrays(int A[], int B[])
    {
        if(A.length>B.length)
        {
            int C[]=A;
            A=B;
            B=C;
        }
        int aLen=A.length;
        int bLen=B.length;
        int k=(aLen+bLen-1)/2;
        int l=0;
        int r=Math.min(aLen, k);
        int midA;
        int midB;
        while(l<r)
        {
            midA=(l+r)/2;
            midB=k-midA;
            if(midB>k||A[midA]<B[midB])
            {
                l=midA+1;
            }
            else
            {
                r=midA;
            }
        }
        double a=Math.max(l>0?A[l-1]:Integer.MIN_VALUE, k-l>=0?B[k-l]:Integer.MIN_VALUE);
        if(((aLen+bLen)&1)==1)
        {
            return a;
        }
        double b=Math.min(l<aLen?A[l]:Integer.MAX_VALUE, k-l+1<bLen?B[k-l+1]:Integer.MAX_VALUE);
        return (a+b)/2;
    }

}


Median of Two Sorted Arrays

标签:style   color   io   ar   java   sp   div   c   on   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39891219

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