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

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

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        // nums1 and nums2 are not empty
        int m = nums1.length;
        int n = nums2.length;
        boolean isEven = ((m+n)%2 == 0);
        if(m > n)
            return findMedian(nums1,nums2,isEven);
        else
            return findMedian(nums2,nums1,isEven);
    }
    public double findMedian(int[] longArray, int[] shortArray, boolean isEven){
        // shortArray is A, A's length is m
        // longArray is B , B's length is n
        int m = shortArray.length;
        int n = longArray.length;
        int imin = 0;
        int imax = m;
        double left_max;
        double right_min;
        while(imin <= imax){
            int i = (imin + imax)/2;
            int j = (m + n)/2 - i;
            // if i<m and m < n, then we can calculate j>0
            // if i>0 and m < n, then we can calculate j<n
            if(i<m && longArray[j-1] > shortArray[i])  imin = i+1; // so use this as part of the condition : i < m 
            else if (i>0 && shortArray[i-1] > longArray[j]) imax = i-1; // so use this as part of the condition : i > 0 
            else{
                //here, if isEven : median = (max(A[i-1],B[j-1]) + min(A[i],B[i])) / 2
                //      else      : median = min(A[i],B[j])
                //however, i,j maybe equal 0,0 or m,n
                //so, we need to classify them
                
                // right 
                if(i==m)        right_min = longArray[j]; 
                else if(j==n)   right_min = shortArray[i];
                else            right_min = Math.min(shortArray[i],longArray[j]);
                
                if(!isEven)     return right_min;
                
                
                // left 
                if(i==0)        left_max = longArray[j-1];
                else if(j==0)   left_max = shortArray[i-1];
                else            left_max = Math.max(shortArray[i-1],longArray[j-1]);
            
                return (right_min + left_max) / 2;
            }
        }
        return 0;
    }
}

 这个题的解法就是在较短的 那个 array 上 做 binary search 

如果 较短的 这半需要增长点, 那么使 left = mid , 如果 这段 需要短一点, 那么 right = mid 

判断需要增长还是 变短 是根据 

      left_part          |        right_part
A[0], A[1], ..., A[i-1]  |  A[i], A[i+1], ..., A[m-1]
B[0], B[1], ..., B[j-1]  |  B[j], B[j+1], ..., B[n-1]


1) len(left_part) == len(right_part)
2) B[j-1] <= A[i] and A[i-1] <= B[j]



剩下的要处理的就是 1. 奇偶 2. when i = 0. j = 0. (不可以再减了) i = n, i = m (到头了)

 

posted on 2018-11-09 10:26  猪猪&#128055;  阅读(149)  评论(0)    收藏  举报

导航