You are given two integer arrays nums1 and nums2 of size m and n respectively, where each is sorted in ascending order. Return the median value among all elements of the two arrays.
Your solution must run in O(log(m+n)) time.
Example 1:
Input: nums1 = [1,2], nums2 = [3]
Output: 2.0 Explanation: Among [1, 2, 3] the median is 2.
Example 2:
Input: nums1 = [1,3], nums2 = [2,4]
Output: 2.5 Explanation: Among [1, 2, 3, 4] the median is (2 + 3) / 2 = 2.5.
In [5]:
def findMedian(nums1, nums2):
m1,m2=0,0
len1,len2=len(nums1),len(nums2)
i,j=0,0
for k in range((len1+len2)//2 + 1):
m2=m1
if i<len1 and j<len2:
if nums1[i]<=nums2[j]:
m1=nums1[i]
i+=1
else:
m1=nums2[j]
j+=1
elif i<len1:
m1=nums1[i]
i+=1
else:
m1=nums2[j]
j+=1
if (len1+len2)%2==1:
return float(m1)
else:
return (m1+m2)/2.0
In [6]:
findMedian([1,3],[2,4,5])
Out[6]:
3.0
In [7]:
findMedian([1,3],[2,4])
Out[7]:
2.5