[leetcode]Median of Two Sorted Arrays

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)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

这题大致有两种解法,第一种使用中位数的定义(将有序数组分为同等两部分)然后通过二分法寻找满足中位数的切割。
第二种解法比较通俗易懂,利用另外一个问题:在两个有序数组中找k-th小的数。
Let’s say we have two arrays:
a0,a1,a2,...,am1
b0,b1,b2,...,bn1
The array after merging two arrays:
c0,c1,c2,...,cm+n1
goal: find kth smallest number of merged array, which is ck1
Theorem: say if ak/21<bk/21 , then numbers ak/21 and its left side elements are all smaller than kth smallest number of the merged array: ck1 .
ak/21 and its left side elements: a0,a1,...,ak/21 .
Assume that ck1=ak/21 :
In the merged array, there are k1 elements smaller than ck1 .
In the first array, there are k/21 elements smaller than ck1=ak/21 .
In the second array, there are at most k/21 elements smaller than ck1=ak/21<bk/21 .
Thus there are at most k2 elements smaller than ck1 , which is a contradiction.

How to use this theorem?
find(a,b,k)
Compare ak/21 with bk/21 ,
if ak/21<bk/21 , return find(a+k/2,b,k/2)
else return find(a,b+k/2,k/2)
So the median of two sorted arrays could be solved in O(log(m+n)) .

class Solution 
{
private:
    int k_th(vector<int>::iterator a, int m, vector<int>::iterator b, int n, int k)
    {
        if (m < n) return k_th(b, n, a, m, k);
        if (n == 0) return *(a + k - 1);
        if (k == 1) return min(*a, *b);

        int j = min(k / 2, n);
        int i = k - j;
        if (*(a + (i - 1)) > *(b + (j - 1)))
            return k_th(a, i, b + j, n - j, k - j);
        return k_th(a + i, m - i, b, j, k - i);
    }
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 
    {
        int m = nums1.size(), n = nums2.size();
        int m1 = k_th(nums1.begin(), m, nums2.begin(), n, (m + n) / 2 + 1);
        if ((m + n) % 2 == 0)
            return (m1 + k_th(nums1.begin(), m, nums2.begin(), n, (m + n) / 2)) / 2.0;
        return m1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值