4. Median of Two Sorted Arrays

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4. Median of Two Sorted Arrays相关的知识,希望对你有一定的参考价值。

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

t int MAX = 0x7fffffff, MIN = 0x80000000;
int kth(vector<int>& nums1, vector<int>& nums2, int sz1, int sz2, int k)
{
#define N1(i) (i<1?MIN:(i>sz1?MAX:nums1[i-1]))
#define N2(i) (i<1?MIN:(i>sz2?MAX:nums2[i-1]))
    int l, r, x;
    l = 0;
    r = sz1;
    while (l <= r)
    {
        x = (l + r) >> 1;
        if (N1(x) > N2(k - x + 1))
            r = x - 1;
        else if (N1(x + 1) < N2(k - x))
            l = x + 1;
        else
            return max(N1(x), N2(k - x));
    }
    return 0; //should not get here
#undef N1
#undef N2
}

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    int sz1 = nums1.size(), sz2 = nums2.size(), sz = sz1 + sz2;
    if (sz1 > sz2)
        return findMedianSortedArrays(nums2, nums1);
    if (sz & 1)
        return kth(nums1, nums2, sz1, sz2, (sz >> 1) + 1);
    return (kth(nums1, nums2, sz1, sz2, sz >> 1) + kth(nums1, nums2, sz1, sz2, (sz >> 1) + 1)) / 2.0;
}

 

以上是关于4. Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-4 Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

Median of two Sorted Arrays

4. Median of Two Sorted Arrays (二分法;递归的结束条件)

4.Median of Two Sorted Arrays

#Leetcode# 4. Median of Two Sorted Arrays