LeetCode 4 寻找两个正序数组的中位数

给定两个大小分别为 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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值