4. Median of Two Sorted Arrays

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        
        if (l2<l1) return findMedianSortedArrays(nums2, nums1);
        // number of elements on the left partition;
        int k = (l1+l2+1)/2;
        
        // start and end index of the selected partition;
        int start = 0;
        int end = l1;
        
        while (start<end){
            // p1 and p2 are the number of elements on the left
            // thus the most left element in the right partition of nums1 is
            // nums1[p1]
            // p1 will be alwarys < end;
            int p1 = (start+end)/2;
            int p2 = k-p1;
            // p1: index of the first element of the left partition
            // p2-1: index of the last element of the right partition of array 2
            if(nums1[p1] < nums2[p2-1]) start = p1+1;
            else end = p1; 
        }
        
        int p1 = start;
        int p2 = k-p1;
        
        int leftMax = Math.max(p1==0? Integer.MIN_VALUE : nums1[p1-1], p2 == 0 ? Integer.MIN_VALUE : nums2[p2-1]);
        
        if ((l1+l2)%2==1) return leftMax;
        else{
            int rightMin = Math.min(p1 == l1? Integer.MAX_VALUE : nums1[p1], p2 == l2 ? Integer.MAX_VALUE : nums2[p2]);
            return (leftMax+rightMin)/2.0;
        }
    }
}

Last updated