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)).

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
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1 == null && nums2 == null) {
            return 0;
        }
        if (nums1 == null || nums1.length == 0) {
            return helper(nums2);
        }
        if (nums2 == null || nums2.length == 0) {
            return helper(nums1);
        }
        int len1 = nums1.length;
        int len2 = nums2.length;
        int len = len1 + len2;
        if (len % 2 == 1) {
            return findKth(nums1, 0, nums2, 0, len / 2 + 1);
        } else {
            return (findKth(nums1, 0, nums2, 0, len / 2) +
                    findKth(nums1, 0, nums2, 0, len /2 + 1)) / 2.0;
        }
    }
    // Should use start rather than end, cause we want to reduce k each iteration so that k can be down to 1;
    private int findKth(int[] a, int startA, int[] b, int startB, int k) {
        if (startA >= a.length) {
            // Should pay attention to startB, need to add startB to k - 1
            return b[startB + k -1];
        }
        if (startB >= b.length) {
            return a[startA + k - 1];
        }
        if (k == 1) {
            return Math.min(a[startA], b[startB]);
        }
// Should be MAX, not MIN
        int keyA = startA + k / 2 - 1 >= a.length ? Integer.MAX_VALUE : a[startA + k / 2 - 1];
        int keyB = startB + k / 2 - 1 >= b.length ? Integer.MAX_VALUE : b[startB + k / 2 - 1];
        
        if (keyA < keyB) {
            return findKth(a, startA + k / 2, b, startB, k - k / 2);
        } else {
            return findKth(a, startA, b, startB + k / 2, k - k / 2);
        }
    }
    
    private double helper(int[] num) {
        int k = num.length;
        if (k % 2 == 1) {
            return num[k / 2];
        } else {
            return (num[k / 2] + num[k / 2 - 1]) / 2.0;
        }
    }
}
Advertisements