- Median of Two Sorted Arrays Hard
4430
607
Favorite
Share 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
Idea: add an array traversal to find the middle element
Code: python3
class Solution:
def findMedianSortedArrays(self, nums1, nums2) -> float:
mid=(len(nums1)+len(nums2))//2
m,n=0,0
arr=[]
for i in range(len(nums1)+len(nums2)):
if len(nums1)<=m:
arr.append(nums2[n])
n+=1
elif len(nums2)<=n:
arr.append(nums1[m])
m+=1
elif nums1[m]<=nums2[n]:
arr.append(nums1[m])
m+=1
else:
arr.append(nums2[n])
n+=1
print(arr)
print(mid)
if (len(nums1)+len(nums2))%2==0:
print(arr)
print(arr[mid])
return float((arr[mid]+arr[mid-1])/2)
else:
return float(arr[mid])
复制代码
Reproduced in: https: //juejin.im/post/5d09fb03f265da1b695d62e7