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

Solution

public class Solution {
     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int size1 = nums1.length;
        int size2 = nums2.length;

        int total = size1 + size2;
        if (total % 2 == 0) {
            return (findK(nums1, 0, nums2, 0, total / 2) + findK(nums1, 0, nums2, 0, total / 2 + 1)) / 2.0;
        } else {
            return findK(nums1, 0, nums2, 0, total / 2 + 1);
        }
    }

    private double findK(int[] A, int startA, int[] B, int startB, int K) {
        if (startA >= A.length) {
            return B[startB + K - 1];
        }

        if (startB >= B.length) {
            return A[startA + K - 1];
        }

        if (K == 1) {
            return A[startA] < B[startB] ? A[startA] : B[startB];
        }

        int AKey = startA + K / 2 > A.length ? Integer.MAX_VALUE : A[startA + K / 2-1];
        int BKey = startB + K / 2 > B.length  ? Integer.MAX_VALUE : B[startB + K / 2-1];

        if (AKey < BKey) {
            return findK(A, startA + K / 2, B, startB, K - K / 2);
        } else {
            return findK(A, startA, B, startB + K / 2, K - K / 2);
        }
    }

}

results matching ""

    No results matching ""