[LeetCode] Median of Two Sorted Arrays

There are two sorted arrays A and B 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)).

转换为求第K大的数

public double findMedianSortedArrays(int A[], int B[]) {
    if (A == null || B == null) {
        return 0;
    }
    
    if (A.length == 0 && B.length == 0) {
        return 0;
    }
    
    int m = A.length;
    int n = B.length;
    if (((m + n) & 1) == 1) {
        return getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2 + 1);
    } else {
        return (getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2 + 1) + getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2)) / 2.0;
    }
    
}

private int getKthNum(int A[], int B[], int startA, int endA, int startB, int endB, int k) {
    int m = endA - startA + 1;
    int n = endB - startB + 1;
    
    // k = 1 直接返回最小的。
    if (k == 1) {
        return Math.min(A[startA], B[startB]);
    }
    
    // 保证 A数组元素小于等于B数组元素
    if (m < n) {
        return getKthNum(B, A, startB, endB, startA, endA, k);
    }
    
    if (m == 0) {
        return B[startB + k - 1];
    }
    
    int posA = Math.min(m, k / 2);
    int posB = k - posA;  // keep posA + posB = k
    
    if (A[startA + posA - 1] == B[startB + posB - 1]) {
        return A[startA + posA - 1];
        // 减去B的左边和 A的右边, 注意边界
    } else if (A[startA + posA - 1] > B[startB + posB - 1]) {
        return getKthNum(A, B, startA, startA + posA - 1 , startB + posB, endB, k - posB);
        // 减去A的左边和 B的右边, 注意边界
    } else {
        return getKthNum(A, B, startA + posA, endA , startB, startB + posB - 1, k - posA);
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值