leetcode Median of Two Sorted Arrays java 两个排序数组的中位数

来源:互联网 发布:评价李鸿章 知乎 编辑:程序博客网 时间:2024/05/16 19:41
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)).
存在两个已排序数组AB,要求找到这两个数组的中位数,要求时间复杂度O(log (m+n)).
拿到这道题如果不考虑时间复杂度,首先我们想到的是将这两个字符串合并成一个已排序的字符串,length = (m+n)/2 如果length是奇数直接返回总字符串的第(m+n)/2位,如果为偶数返回中间两位的平均数。
但这种方法需要做一次排序,进一步优化,想通过定义两个指针一次查找这两个数组到第length/2次结束,分别找到第length/2 和 length/2-1位。代码实现如下:
public class FindMedianSortedArrays {    public static void main(String[] args){        int[] A = new int[]{};        int[] B = new int[]{2,3};        System.out.print(findMedianSortedArrays(A,B));    }    public static double findMedianSortedArrays(int A[], int B[]) {        if(A==null && B==null) return 0;    // 限定AB都不能为0        int m=0,n=0;            // 存储AB的长度        double k=0,preK=0;      // 存放length/2 以及 length/2-1 位的数字        int length = 0;         // 存放整体长度        if(A==null) m=0; else m = A.length;     // 对mn赋值        if (B==null) n=0; else n = B.length;        length = m+n;           // 对length赋值        if(length<2){           // 如果AB中一个长度为0 另一个为1则直接返回            if(m==0) return B[0];            else return A[0];        }        int count = 0;        int i=0,j=0;        if(m==0){               // 只有B存在,A的长度为0,直接返回B的中位数            if (length%2==0){                return ((double)B[length/2]+(double)B[length/2-1])/2;            }else                return B[length/2];        }else{            if (n==0){          // 只有a存在                if (length%2==0){                    return ((double)A[length/2]+(double)A[length/2-1])/2;                }else                    return A[length/2];            }        }        while (count<=length/2){    // 都存在时从头遍历,找到中间及其之前的一位数                if((i<m && j<n && A[i]<=B[j])||(j>=n)){                    preK = k;                    k = A[i];                    ++i;                }else{                    if((i<m && j<n && A[i]>B[j])||(i>=m)){                        preK = k;                        k = B[j];                        ++j;                    }                }            ++count;        }        if (length%2 == 1){            return k;        }else {            return (k+preK)/2;        }    }}

0 0
原创粉丝点击