4. Median of Two Sorted Arrays

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

思路:是找find kth的扩展情况,一直保持第一个array比第一个小,每次砍掉一部分搜索空间

public class Solution {
     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int total = m + n;  
        if (total%2!=0)  
            return findKth(nums1, m, nums2, n, total / 2 + 1);  
        else  
            return (findKth(nums1, m, nums2, n, total / 2)  
                    + findKth(nums1, m, nums2, n, total / 2 + 1)) / 2;  
    }

    double findKth(int a[], int m, int b[], int n, int k)  
    {  
        //always assume that m is equal or smaller than n  
        if (m > n)  
            return findKth(b, n, a, m, k);  
        if (m == 0)   //left is empty, then we can just find kth in b
            return b[k - 1];  
        if (k == 1)  // only need to find the first element
            return Math.min(a[0], b[0]);  
        //divide k into two parts  
        int pa = Math.min(k / 2, m), pb = k - pa;  
        if (a[pa - 1] < b[pb - 1])   // can throw away left side of a
            return findKth(Arrays.copyOfRange(a, pa, m), m - pa, b, n, k - pa);  
        else if (a[pa - 1] > b[pb - 1])   // can throw away right side of a
            return findKth(a, m, Arrays.copyOfRange(b, pb, n), n - pb, k - pb);  
        else  
            return a[pa - 1];  
    }  
}

results matching ""

    No results matching ""