LeetCode Median of Two Sorted Arrays

来源:互联网 发布:最游记一键淘宝端 编辑:程序博客网 时间:2024/04/30 13:23

Median of Two Sorted Arrays

题目描述:There are two sorted arrays A and B of size mand n respectively. Find the median of the two sorted arrays. The overall runtime complexity should be O(log (m+n)).

这道题以前碰到过要求找到第K小的数。

最简单的想法就是遍历AB两个数组,找到第K小的数。

当时做的时候也是达不到其要求的O(log(m+n))的时间复杂度。于是只能求助万能的互联网了。

这里假设AB两个数组都是从小到大排序的,分别为{13469}{2578},要求他们第4小的数。这里先比较A的第二小的数和B的第二小的数,分别是35,这里就可以舍弃A的前两位数,因为他们不可能是第4大的数,于是题目就成为{469}{2578}找到他们第二小的数,比较A的最小和B最小的数,舍弃B最小的数,编程{469}{578},找到他们最小的数,是4,就得到正确答案了。

public class Solution {    public double findMedianSortedArrays(int A[], int B[]) {        int m = A.length;        int n = B.length;        if(m==0&&n==0) return 0;        int total = m + n;        if ((total % 2)==1)            return findk(A,B,total/2+1);        else            return (findk(A,B,total/2+1)+findk(A,B,total/2))/2.0;    }        double findk(int A[], int B[] ,int k){        if(A.length>B.length){//做了这个处理之后 只用考虑A数组的长度小于k/2这一种情况了。            return findk(B,A,k);        }        if(A.length==0){            return B[k-1];        }        if(k==1){            return Math.min(A[0],B[0]);        }        int pa = Math.min(k/2,A.length);        int pb = k-pa;        if(A[pa-1]<B[pb-1]){            return findk(Arrays.copyOfRange(A,pa,A.length),B,k-pa);        }        else if(A[pa-1]>B[pb-1])            return findk(A,Arrays.copyOfRange(B,pb,B.length),k-pb);        else            return A[pa-1];    }}


0 0
原创粉丝点击