进击的程序猿

记录每天的心得,转载好的文章

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.

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013731743/article/details/46822791
文章标签: java leetcode
个人分类: Leetcode心得
上一篇Java 成员初始化过程
下一篇java 中的 ==和equals
博主设置当前文章不允许评论。

没有更多推荐了,返回首页

关闭
关闭