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

int findKth(int *arr1, int len1, int *arr2, int len2, int k){
    if(len1 > len2) return findKth(arr2, len2, arr1, len1, k);

    if(len1 == 0)   return arr2[k - 1];

    if(k == 1)  return (arr1[0] < arr2[0])?arr1[0]:arr2[0];

    int split1 = (len1 < k/2) ? len1:k/2;
    int split2 = k - split1;

    if(arr1[split1 - 1] < arr2[split2 - 1])
        return findKth(arr1 + split1, len1 - split1, arr2, len2, k - split1);
    else if(arr1[split1 - 1] > arr2[split2 - 1])
        return findKth(arr1, len1, arr2 + split2, len2 - split2, k - split2);
    else
        return arr1[split1 - 1];
}

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    //assert(nums1Size >= 0);assert(nums2Size >= 0);

    int len = nums1Size + nums2Size;

    if(len&1)
        return (double)findKth(nums1, nums1Size, nums2, nums2Size, len/2 + 1);
    else
        return (double)(findKth(nums1, nums1Size, nums2, nums2Size, len/2)+
        findKth(nums1, nums1Size, nums2, nums2Size, len/2 + 1))/2.0;
}

results matching ""

    No results matching ""