给定两个大小分别为 m 和 n 的正序(从小到大)数组nums1 和nums2。请你找出并返回这两个正序数组的 中位数 。 算法的时间复杂度应该为 O(log (m+n)) 。 示例 1: 输入:nums1 = [1,3], nums2 = [2] 输出:2.00000 解释:合并数组 = [1,2,3] ,中位数 2 示例 2: 输入:nums1 = [1,2], nums2 = [3,4] 输出:2.50000 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
def findMedianSortedArrays( nums1, nums2) :
a =[]
a = nums1 + nums2 #两个数组的拼接
a.sort() #将数组排成正序
if len(a) % 2 == 1: #判断余数是否为1
b=int((len(a))/2) #除法的结果是浮点数,而索引必须是整型
median=a[b]
else:
c=int((len(a))/2-1)
d=int((len(a))/2)
median = (a[c]+a[d])/2
return median
nums1=[1,3,4]
nums2=[2]
findMedianSortedArrays(nums1, nums2)