004 Median of Two Sorted Arrays [Leetcode]

44 篇文章 0 订阅
1 篇文章 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)).

解题思路:
复杂度要求为O(log (m+n)),很容易让人想到二分查找。如果是一个长度为(m+n)的排序数组,那么直接使用二分查找就可以。但本题是在两个数组上进行的,那么在两个数组上进行二分查找会如何呢?
找中位数,若为奇数个,就是找第(m+n)/2个数;若为偶数个,就是找第(m+n)/2和第(m+n)/2+1个数的平均值。设我们要找的数是第k个。
1. 如果第一个数组的中间值与第二个数组的中间值相同,那么说明我们找到了中间值,即中间的这个数。
2. 如果第一个数组的中间值小于第二个数组的中间值,说明第一个数组中间值以前都不可能是前k个数,因此在剩余的数组中继续找前k-m/2个数
3. 如果第一个数组的中间值大于第二个数组的中间值,说明第二个数组中间值以前都不可能是前k个数,因此在剩余的数组中继续找前k-n/2个数
4. 注意处理数组变为空的情况

代码如下:

class Solution {
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        int length(m+n);
        if(length%2)
            return findKth(A, m, B, n, length/2+1);
        else
            return (findKth(A, m, B, n, length/2)+findKth(A, m, B, n, length/2+1))/2.0;
    }

    int findKth(int A[], int m, int B[], int n, int K) {
        if(m>n)
            return findKth(B, n, A, m, K);
        if(m==0)
            return B[K-1];
        if(K==1)
            return A[0]<B[0]?A[0]:B[0];

        int pa(K/2<m?K/2:m);
        int pb(K-pa);
        if(A[pa-1]==B[pb-1])
            return A[pa-1];
        else if(A[pa-1]>B[pb-1])
            return findKth(A, m, B+pb, n-pb, K-pb);
        else
            return findKth(A+pa, m-pa, B, pb, K-pa);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值