leetcode算法题4: 寻找两个有序数组的中位数

题目:给定两个大小为 m 和 n 的有序数组 nums1 和 nums2

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

示例 1:nums1 = [1, 3] nums2 = [2],  则中位数是 2.0

示例 2:nums1 = [1, 2] nums2 = [3, 4] ,则中位数是 (2 + 3)/2 = 2.5

解析:两个数组分别采用二分法查找。如下示例:

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int length1 = nums1.length;
        int length2 = nums2.length;
        int lengthall = length1 + length2;
        int l = (lengthall+1)/2;
        int r = (lengthall+2)/2;
 
        return (getKMin(nums1,0,nums2,0,l)+getKMin(nums1,0,nums2,0,r))*1.0/2;  
    }
    
     public static int getKMin(int[] A, int Astart, int[] B, int Bstart, int k){
        if (Astart>A.length-1){
            return B[Bstart + k -1];
        }
        if (Bstart>B.length-1){
            return A[Astart + k -1];
        }
        if (k==1){
            return Math.min(A[Astart],B[Bstart]);
        }
 
        int Amin = Integer.MAX_VALUE,Bmin = Integer.MAX_VALUE;
        if (Astart + k/2 -1 < A.length){
            Amin = A[Astart + k/2 -1];
        }
        if (Bstart + k/2 -1 < B.length){
            Bmin = B[Bstart + k/2 -1];
        }
 
        return Amin < Bmin ? getKMin(A,Astart + k/2, B, Bstart,k-k/2):getKMin(A,Astart,B,Bstart+k/2,k-k/2);
    }

}

复杂度分析

  • 时间复杂度:O(log(m+n))

猜你喜欢

转载自blog.csdn.net/MySunshine07/article/details/84330863