4. Median of Two Sorted Arrays

There are two sorted arrays nums1and 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:

Find medium of the two sorted arrays ----> find the k/2 element of nums1 + nums2 where k is the total length of the two arrays.

  1. find the k/2th element in nums1[k/2] and k/2th element in nums2[k/2]
    1. if nums1[k/2] <= nums2[k/2], all k/2 elements in nums1 should be included in the combined array
    2. if nums1 length < k/2, all the k/2 elements in nums2 should be included in the combined array
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int length = nums1.length + nums2.length;
        if(length % 2 == 0){
            return ((findKthNumber(nums1, 0, nums2, 0, length/2) + 
                     findKthNumber(nums1, 0, nums2, 0, length/2 + 1))/2.0);
        }
        else{
            return findKthNumber(nums1, 0, nums2, 0, length/2 + 1);
        }
    }

    private int findKthNumber(int[] nums1, int nums1_start,
                              int[] nums2, int nums2_start,
                              int k){
        if(nums1_start >= nums1.length)
            return nums2[nums2_start + k - 1];
        if(nums2_start >= nums2.length)
            return nums1[nums1_start + k - 1];

        if(k == 1)
            return Math.min(nums1[nums1_start], nums2[nums2_start]);
        int nums1_key = nums1_start + k/2 - 1 < nums1. length 
                        ? nums1[nums1_start + k/2 - 1]
                        : Integer.MAX_VALUE;
        int nums2_key = nums2_start + k/2 - 1 < nums2.length
                        ? nums2[nums2_start + k/2 - 1]
                        : Integer.MAX_VALUE;

        if (nums1_key <= nums2_key){
            return findKthNumber(nums1, nums1_start + k/2, nums2, nums2_start,
                                 k - k/2);
        }else{
            return findKthNumber(nums1, nums1_start, nums2, nums2_start + k/2,
                                 k - k/2);
        }

    }

results matching ""

    No results matching ""