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

【LeetCode】Median of Two Sorted Arrays (2 solutions)

时间:2014-12-23 19:10:42      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

Median of Two Sorted Arrays

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

 

解法一:保底做法,O(m+n)复杂度

按照归并排序的思路,数到median,然后计算返回。

需要注意:

如果是m+n是偶数,需要返回两个中位数的均值

class Solution {
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        if(m==0 && n==0)
            return 0;
        else if(m==0 && n!=0)
            return ((double)(B[(n-1)/2]+B[n/2]))/2;
        else if(m!=0 && n==0)
            return ((double)(A[(m-1)/2]+A[m/2]))/2;
        
        //m!=0 && n!=0
        int total = m+n;
        bool isEven = (total%2==0)?true:false;
        int ind = (total-1)/2;
        int i = 0;
        int j = 0;
        int tag = false;    //false--no candidate; true--one candidate
        int ret1;
        int ret2;
        while(i<m && j<n)
        {
            if(ind==0 && tag==false)
            {
                ret1 = min(A[i],B[j]);
                tag = true;
                if(!isEven)
                    return ret1;
            }
            else if(ind==-1 && tag==true)
            {
                ret2 = min(A[i],B[j]);
                return ((double)(ret1+ret2))/2;
            }
            
            if(A[i] <= B[j])
                i ++;
            else
                j ++;
            ind --;
        }
        while(i<m)
        {
            if(ind==0 && tag==false)
            {
                if(!isEven)
                    return A[i];
                else
                    return ((double)(A[i]+A[i+1]))/2;
            }
            else if(ind==-1 && tag==true)
            {
                ret2 = A[i];
                return ((double)(ret1+ret2))/2;
            }
            i ++;
            ind --;
        }
        while(j<n)
        {
            if(ind==0 && tag==false)
            {
                if(!isEven)
                    return B[j];
                else
                    return ((double)(B[j]+B[j+1]))/2;
            }
            else if(ind==-1 && tag==true)
            {
                ret2 = B[j];
                return ((double)(ret1+ret2))/2;
            }
            j ++;
            ind --;
        }
    }
};

技术分享

【LeetCode】Median of Two Sorted Arrays (2 solutions)

标签:

原文地址:http://www.cnblogs.com/ganganloveu/p/4180523.html

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