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
Java:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int total = nums1.length + nums2.length;
if (total % 2 == 0) {
return (helper(nums1, 0, nums1.length, nums2, 0, nums2.length, total / 2) +
helper(nums1, 0, nums1.length, nums2, 0, nums2.length, total / 2 +1)) / 2.0;
}
return helper(nums1, 0, nums1.length, nums2, 0, nums2.length, total / 2 + 1);
}
public double helper(int[] nums1, int b1, int e1, int[] nums2, int b2, int e2, int k) {
if (b1 == e1) {
return nums2[b2 + k - 1];
} else if (b2 == e2) {
return nums1[b1 + k - 1];
} else if (k == 1) {
return Math.min(nums1[b1], nums2[b2]);
}
int m1 = k / 2, m2 = k - m1;
if(b1 + m1 > e1) {
m1 = e1 - b1;
m2 = k - m1;
} else if (b2 + m2 > e2) {
m2 = e2 - b2;
m1 = k - m2;
}
if (nums1[b1 + m1 - 1] == nums2[b2 + m2 - 1]) {
return (double)nums1[b1 + m1 - 1];
} else if (nums1[b1 + m1 - 1] < nums2[b2 + m2 - 1]) {
return helper(nums1, b1+m1, e1, nums2, b2, b2+m2, m2);
} else {
return helper(nums1, b1, b1+m1, nums2, b2+m2, e2, m1);
}
}
public double helper(int[] nums1, int b1, int[] nums2, int b2, int k) {
if (b1 >= nums1.length) return nums2[b2 + k - 1];
else if (b2 >= nums2.length) return nums1[b1 + k - 1];
else if (k == 1) return Math.min(nums1[b1], nums2[b2]);
int mid1 = b1 + k/2 <= nums1.length ? nums1[b1 + k/2 - 1] : Integer.MAX_VALUE,
mid2 = b2 + k/2 <= nums2.length ? nums2[b2 + k/2 - 1] : Integer.MAX_VALUE;
if (mid1 < mid2) {
return helper(nums1, b1 + k/2, nums2, b2, k - k/2);
} else {
return helper(nums1, b1, nums2, b2 + k/2, k - k/2);
}
}
}
Python:
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
total = len(nums1) + len(nums2)
k = total // 2 if total % 2 == 0 else total // 2 + 1
while len(nums1) != 0 and len(nums2) != 0 and k > 1:
if len(nums1) < k // 2:
nums2 = nums2[k // 2:]
elif len(nums2) < k // 2:
nums1 = nums1[k // 2:]
else:
if nums1[k//2 - 1] < nums2[k//2 - 1]:
nums1 = nums1[k // 2:]
else:
nums2 = nums2[k // 2:]
k -= k // 2
if len(nums1) == 0 or len(nums2) == 0:
nums = nums1 if len(nums2) == 0 else nums2
if total % 2 != 0:
return nums[k - 1]
else:
return (nums[k - 1] + nums[k]) / 2.0
if total % 2 != 0:
return min(nums1[0], nums2[0])
else:
nums = sorted(nums1[:2] + nums2[:2])
return (nums[0] + nums[1]) / 2.0