4. Median of Two Sorted Arrays

Description

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

Solution

Divide & Conquer, time O(log (m+n))?

值得深思的一道题...更好的思路待整理。

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) {
            return 0;
        }
        
        int len = nums1.length + nums2.length;
        return 0.5 * (findKth(nums1, 0, nums2, 0, (len - 1) / 2 + 1)
                    + findKth(nums1, 0, nums2, 0, len / 2 + 1));
    }
    // return the kth element in the combination of a and b, k starts from 1, not 0
    public int findKth(int[] a, int sa, int[] b, int sb, int k) {
        if (a.length - sa > b.length - sb) {    // make sure b has more numbers left
            return findKth(b, sb, a, sa, k);
        }
        
        if (sa == a.length) {
            return b[sb + k - 1];
        }
        
        if (k == 1) {   // need to be handled specially otherwise unfinite-loop happens
            return Math.min(a[sa], b[sb]);
        }
        
        int ka = Math.min(k / 2, a.length - sa);    // tricky
        int kb = k - ka;                            // make ka + kb == k
        
        if (a[sa + ka - 1] < b[sb + kb - 1]) {
            return findKth(a, sa + ka, b, sb, k - ka);
        } else if (a[sa + ka - 1] > b[sb + kb - 1]) {
            return findKth(a, sa, b, sb + kb, k - kb);
        } else {
            return a[sa + ka - 1];
        }
    }
}

你可能感兴趣的:(4. Median of Two Sorted Arrays)