Median of Two Sorted Arrays

Median of Two Sorted Arrays
很经典的题目
题目要求时间复杂度O(log(m+n))
看别人的思路写出来的,核心是findkth方法的递归
不止是中位数,所有的找第几个大的数都可以用这个方法

代码块

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int aend=nums1.length-1;
        int bend=nums2.length-1;
        int astart=0,bstart=0;
        int total=nums1.length+nums2.length;
        if(total%2==1){
            return findkth(nums1,nums2,total/2+1,astart,aend,bstart,bend);
        }else{
            return (findkth(nums1,nums2,total/2+1,astart,aend,bstart,bend)+
            findkth(nums1,nums2,total/2,astart,aend,bstart,bend))/2;
        }
        }
        public double findkth(int a[],int b[],int k,int astart,int aend,int bstart,int bend){
            if(aend-astart>bend-bstart){
                return findkth(b,a,k,bstart,bend,astart,aend);//保持数组a是长度较小的那一个
            }
            if(aend-astart+1==0){//若a数组为空,那么就直接返回b的第k个数
                return b[bstart+k-1];
            }

            if(k==1&&aend-astart+1!=0){//若k=1 那么就直接返回a,b第一个较小的数
                return Math.min(a[astart],b[bstart]);
            }
            int pa=Math.min(k/2,aend-astart+1),pb=k-pa;//将k分为两部分,如果a的第k/2个数比b的第K/2个数小,那么直接把a的前k/2个数去掉
            if(a[astart+pa-1]<b[bstart+pb-1]){        //同时k也减去k/2,继续递归,直到a的长度为空或者k为1,结束递归
                astart+=pa;
                return findkth(a,b,k-pa,astart,aend,bstart,bend);
            }else if(a[astart+pa-1]>b[bstart+pb-1]){
                bstart+=pb;
                return findkth(a,b,k-pb,astart,aend,bstart,bend);
            }else{
                return a[astart+pa-1];
            }

            }
}

核心思想
Assume that the number of elements in A and B are both larger than k/2, and if we compare the k/2-th smallest element in A(i.e. A[k/2-1]) and the k-th smallest element in B(i.e. B[k/2 - 1]), there are three results:
(Becasue k can be odd or even number, so we assume k is even number here for simplicy. The following is also true when k is an odd number.)
A[k/2-1] = B[k/2-1]
A[k/2-1] > B[k/2-1]
A[k/2-1] < B[k/2-1]
if A[k/2-1] < B[k/2-1], that means all the elements from A[0] to A[k/2-1](i.e. the k/2 smallest elements in A) are in the range of k smallest elements in the union of A and B. Or, in the other word, A[k/2 - 1] can never be larger than the k-th smalleset element in the union of A and B.

We should also consider the edge case, that is, when should we stop?
1. When A or B is empty, we return B[k-1]( or A[k-1]), respectively;
2. When k is 1(when A and B are both not empty), we return the smaller one of A[0] and B[0]
3. When A[k/2-1] = B[k/2-1], we should return one of them

In the code, we check if m is larger than n to garentee that the we always know the smaller array, for coding simplicy.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值