https://leetcode.com/problems/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)). You may assume nums1 and nums2 cannot be both empty. 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
class Solution {
public:
double findMedianSortedArrays(vector& nums1, vector& nums2) {
}
};
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
# nums1 always longer than nums2
if len(nums1) == 1:
if len(nums2) % 2 == 0:
return nums2[len(nums2) / 2] /2 + nums2[len(nums2)/2 -1] /2
l1 = 0
h1 = len(nums1) -1
l2 = len(nums2) / 2 - len(nums1) / 2
h2 = len(nums2) / 2 + len(nums1) / 2
m1 = (l1 + h1) / 2
m2 = (l2 + h2) / 2
while (h1 > l1):
m1 = (l1 + h1) / 2
m2 = (l2 + h2) / 2
if nums1[m1] == nums2[m2]:
return nums1[m1]
elif nums1[m1] < nums2[m2]:
l1 = m1 + 1
h2 = m2 - 1
else:
h1 = m1 -1
l2 = m2 + 1
return (nums1[m1] + nums2[m2]) / 2