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

Leetcode 04 Median of Two Sorted Arrays

时间:2015-06-24 00:43:01      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

There are two sorted arrays nums1 and nums2 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)).

class Solution
{
private:
    typedef vector<int>::const_iterator ITE;
public:
    double findkth(ITE l1, ITE r1, ITE l2, ITE r2, int k)
    {
        if (r1 - l1 > r2 - l2) return findkth(l2, r2, l1, r1, k);
        if (l1==r1) return *(l2+k-1);
        if (k == 1) return min(*l1, *l2);
        int pa = min(int(r1 - l1), k / 2), pb = k - pa;
        ITE lpa = l1 + pa - 1, lpb = l2 + pb - 1;
        if (*lpa < *lpb) return findkth(l1 + pa, r1, l2, r2, pb);
        else
            if (*lpa > *lpb)
            {
                return findkth(l1, r1, l2 + pb, r2, pa);
            }
            else
            {
                return *lpa;
            }
    }
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
    {
        int m = nums1.size(), n = nums2.size(), total = m + n;
        ITE l1 = nums1.begin(), r1 = nums1.end();
        ITE l2 = nums2.begin(), r2 = nums2.end();
        if (total % 2) return findkth(l1, r1, l2, r2, total / 2 + 1);
        else
        {
            return (findkth(l1, r1, l2, r2, total / 2) + findkth(l1, r1, l2, r2, total / 2 + 1))/2;
        }
    }
};

 

Leetcode 04 Median of Two Sorted Arrays

标签:

原文地址:http://www.cnblogs.com/chenwanqq-leetcode/p/4596638.html

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