Median of two Sorted Arrays

class Solution {
    /**
     * @param A: An integer array.
     * @param B: An integer array.
     * @return: a double whose format is *.5 or *.0
     */
    public double findMedianSortedArrays(int[] A, int[] B) {
        // write your code here
        int length = A.length + B.length;
        if (length % 2 == 0) {
            return (find(length / 2, A, 0, B, 0) + find (length / 2 + 1, A, 0, B, 0)) / 2.0;
        } else {
            return find(length / 2 + 1, A, 0, B, 0);
        }
    }
    
    double find(int k, int[] A, int astart, int[] B, int bstart) {
        if (astart >= A.length) {
            return B[bstart + k - 1];
        }
        if (bstart >= B.length) {
            return A[astart + k - 1];
        }
        
        if (k == 1) {
            return Math.min(A[astart], B[bstart]);
        }
        
        int akey = astart + k / 2 - 1 < A.length
                    ? A[astart + k / 2 - 1]
                    : Integer.MAX_VALUE;
        int bkey = bstart + k / 2 - 1 < B.length
                    ? B[bstart + k / 2 - 1]
                    : Integer.MAX_VALUE;
        if (akey < bkey) {
            return find(k - k / 2, A, astart + k / 2, B, bstart);
        } else {
            return find(k - k / 2, A, astart, B, bstart + k / 2);
        }
        
        
    }
}

Problems: find the median of two sorted arrays A, B.

Prototype problem: find the K-th largest elements of two sorted arrays A, B.

Challenges:

(1) If A.length + B.length is even, the median is the average of the middle two elements.

      If its odd, the median is the very element in the middle

(2) If we run out of A or B, then the K-th largest element is theOtherArray[k-1]. 2 EDGE CASES HERE

(3) neither A nor B is run out of, we need to find the K / 2 -th largest element in the two arrays. 

      The K / 2 -th largest element of a single array is actually in the index of [K / 2 - 1]. Since we divided K by two, K == 1 is an EDGE CASE.

(4) How do you throw away ~ K / 4 elements every time?

If(akey) < (bkey) then throw away A[astart ... K / 2 - 1]



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值