[LeetCode.Trick]Median of Two Sorted Arrays

一题一句:做这个题的关键是经典方法——找到俩个sorted array里面第K大的元素。 我们无法通过比较A_key 和 B_key知道K在哪,但是可以确定K不在哪。每一层可以排除A的1/2或是B的1/2
Notice :  k - k/2  != k/2 

public class Solution {
    public static double findMedianSortedArrays(int A[], int B[]) {
        int total = A.length + B.length;
        if(total%2 == 0){
            return (findKth(A,0,B,0,total/2) + findKth(A,0,B,0,total/2+1))/2.0;
        }else{
            return findKth(A,0,B,0,total/2 + 1);
        }
    }
    public static double findKth(int[] A, int A_start, int[] B, int B_start,int k){
        if(A_start >= A.length){
            return B[B_start+k-1];
        }
        if(B_start >= B.length){
            return A[A_start+k-1];
        }
        if(k == 1){
            return Math.min(A[A_start],B[B_start]);
        }
        int AKey = A_start+k/2-1 < A.length ? A[A_start + k/2 -1] : Integer.MAX_VALUE;
        int BKey = B_start+k/2-1 < B.length ? B[B_start + k/2 -1] : Integer.MAX_VALUE;
        if(AKey > BKey){
            return findKth(A,A_start,B,B_start+k/2,k-k/2);
        }else{
            return findKth(A,A_start+k/2,B,B_start,k-k/2);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值