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

You may assume nums1 and nums2 cannot be both empty.

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
    public static double findMedianSortedArrays(int[] A, int[] B) {
        // write your code here
        int len = A.length + B.length;
        if (len % 2 == 1) {
            return finKth(A, 0, B, 0, len / 2 + 1);
        } else {
            return (
                    finKth(A, 0, B, 0, len / 2) + finKth(A, 0, B, 0, len / 2 + 1)
            ) / 2.0;
        }
    }

    private static double finKth(int[] A, int indA, int[] B, int indB, int k) {
	    //情况一:有一个数组为空
	    //如果数组的起始位置>=数组的长度,则在另一个数组里找第k个数,第k个数的index为另一个数组起始位置+k+1
        if (indA >= A.length) {
            return B[indB + k - 1];
        }
        if (indB >= B.length) {
            return A[indA + k - 1];
        }
        //情况二:k=1
        //如果k=1,则只需要比较两个数组里第一个元素的大小,返回较小的哪一个
        if (k == 1) {
            return Math.min(A[indA], B[indB]);
        }
        //情况三:一般情况
        //如果数组A的第k/2个元素存在的话,获取数组A的第k/2个元素
        int A_key = indA + k / 2 - 1 < A.length
                ? A[indA + k / 2 - 1]
                : Integer.MAX_VALUE;
        int B_key = indB + k / 2 - 1 < B.length
                ? B[indB + k / 2 - 1]
                : Integer.MAX_VALUE;
        //如果数组A的第k/2个元素>数组B的第k/2个元素,说明要找的数肯定不在数组B的前k/2个元素中,此时需要数组B的起始位置+k/2
        //因为数组的总长度发生变化,所以K的值也要变,k=k-k/2
        if (A_key > B_key) {
            return finKth(A, indA, B, indB + k / 2, k - k / 2);
        } else {
            return finKth(A, indA + k / 2, B, indB, k - k / 2);
        }

    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值