LeetCode 004 Median of Two Sorted Arrays

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Requirements: The overall run time complexity should be O(log (m+n)).

so what is median?
median is the number which locates in the middle when we merged these two sorted arrays, if: after we merge them the totoal number of elements is even, then we need to get a average of center 2 and if it is odd then we only need one.

how are we gonna find the center from two seperate arrays?
because we know the total number of elements, so we know that we should iterate(merge those two arrays one by one) those two, like merge two sorted list, but we should stop when we iterate to the place of (m+n)/2

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n1 = nums1.length;
        int n2 = nums2.length;
        
        if (n1 > n2) return findMedianSortedArrays(nums2, nums1);//the first should be the shorter one
        
        int k = (n1 + n2 + 1) / 2;
        
        int l = 0;
        int r = n1;
        
        while (l < r) {
            int m1 = (r - l) / 2 + l; //do binary search for nums1 
            int m2 = k - m1;
            
            if (nums1[m1] < nums2[m2 - 1]) {
                l = m1 + 1;
            } else {
                r = m1;
            }
        }
        
        int m1 = l;
        int m2 = k - l;
        
        int c1 = Math.max(m1 <= 0 ? Integer.MIN_VALUE: nums1[m1 - 1], m2 <= 0 ? Integer.MIN_VALUE: nums2[m2 - 1]);
        
        if ((n1 + n2) % 2 == 1) { //if sum of length is odd  number
            return c1; //return 
        }
        
        int c2 = Math.min(m1 >= n1 ? Integer.MAX_VALUE: nums1[m1], m2 >= n2 ? Integer.MAX_VALUE: nums2[m2]);
        return (c1 + c2) * 0.5; //why /2 is not accepted, but times 0.5 is?
    }
}

posted @ 2020-11-08 04:04  EvanMeetTheWorld  阅读(13)  评论(0)    收藏  举报