4. Median of Two Sorted Arrays

Explanation

Binary Search

The key point of this problem is to ignore half part of A and B each step recursively by comparing the median of remaining A and B:

if (aMid < bMid) Keep [aRight + bLeft]    
else Keep [bRight + aLeft]

As the following:

time=O(log(m + n))

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n = nums1.length, m = nums2.length;
        int l1 = (n + m + 1) / 2;
        int l2 = (n + m + 2) / 2;

        return (findKth(nums1, 0, nums2, 0, l1) + findKth(nums1, 0, nums2, 0, l2)) / 2.0;
    }

    private double findKth(int[] nums1, int start1, int[] nums2, int start2, int k){
        if (start1 >= nums1.length) return nums2[start2 + k - 1];
        if (start2 >= nums2.length) return nums1[start1 + k - 1];
        if (k == 1) return Math.min(nums1[start1], nums2[start2]);

        int mid1 = Integer.MAX_VALUE, mid2 = Integer.MAX_VALUE;
        if (start1 + k / 2 - 1 < nums1.length) mid1 = nums1[start1 + k / 2 - 1];
        if (start2 + k / 2 - 1 < nums2.length) mid2 = nums2[start2 + k / 2 - 1];

        if (mid1 < mid2){
            return findKth(nums1, start1 + k / 2, nums2, start2, k - k / 2);
        }
        else{
            return findKth(nums1, start1, nums2, start2 + k / 2, k - k / 2);
        }
    }
}

results for ""

    No results matching ""