两个有序数组合并,并求中位数(复杂度为O(m+n))

先将两个有序数组合并成为一个有序数组,然后再求中位数。合并时,判断条件是i<m || j<n

特别注意,中位数用double,int数据进行计算时,要先转化为double(直接赋值即可),然后再计算


public double findMedianSortedArrays(int A[], int B[]) {
        int l1 = A.length;
        int l2 = B.length;
        int [] C = new int[l1+l2];
        int i =0,j =0,k=0;
        while(i<l1 || j<l2){
            if(i >= l1){
                C[k] = B[j];
                j++;
            }else if(j >= l2){
                C[k] = A[i];
                i++;
            }else{
                if(A[i]<B[j]){
                   C[k] =  A[i];
                   i++;
                }else{
                   C[k] =  B[j];
                   j++;
                }
            }
            k++;
        }
        double median = 0,a=0,b=0;
        k = l1+l2;
        if(k%2 != 0){
            median = C[(k-1)/2];
        }else{
            a = C[k/2];
            b = C[k/2-1];
            median = (a+b)/2;
        }
        return median;
    }


你可能感兴趣的:(两个有序数组合并,并求中位数(复杂度为O(m+n)))