4. Median of Two Sorted Arrays - Hard

There are two sorted arrays nums1 and nums2 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)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

基于kth smallest element in two sorted array

time: O(log(M + N)), space: O()

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int k = (nums1.length + nums2.length) / 2;
        int m1 = kth(nums1, nums2, 0, 0, k + 1);
        if((nums1.length + nums2.length) % 2 == 0) {
            int m2 = kth(nums1, nums2, 0, 0, k);
            return (double)(m1 + m2) / 2.0;
        }
        return m1;
    }
    
    private static int kth(int[] A, int[] B, int aleft, int bleft, int k) {
        if(aleft >= A.length)
            return B[bleft + k - 1];
        if(bleft >= B.length)
            return A[aleft + k - 1];
        if(k == 1)
            return Math.min(A[aleft], B[bleft]);

        int amid = aleft + k / 2 - 1;
        int bmid = bleft + k / 2 - 1;

        int aval = amid >= A.length ? Integer.MAX_VALUE : A[amid];
        int bval = bmid >= B.length ? Integer.MAX_VALUE : B[bmid];

        if(aval <= bval) {
            return kth(A, B, amid + 1, bleft, k - k / 2);
        } else {
            return kth(A, B, aleft, bmid + 1, k - k / 2);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10130954.html