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

给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。

算法的时间复杂度应该为 O(log (m+n))

 

复制代码
nums2 = [1,]
nums1 = [54,78,90,]

def test(nums):
    lengh = len(nums)
    if lengh % 2 == 0:
        index = [lengh / 2 - 1, lengh / 2]
    else:
        index = [lengh // 2]
    if len(index) == 2:
        # print(index)
        print(nums[int(index[0])], nums[int(index[1])])
    else:
        print(nums[int(index[0])])


if not nums2 or not nums1:
    if nums1:
        test(nums1)
    else:
        test(nums2)
else:
    lengh = len(nums1) + len(nums2)
    index = []
    if lengh == 1:
        index.append(0)
    elif lengh % 2 != 0:
        index.append((lengh - 1) // 2)
    else:
        index.append(lengh // 2 - 1)
        index.append(lengh // 2)

    result = []
    for it in range(index[-1] + 1):
        if nums1 and nums2:
            if nums1[0] > nums2[0]:
                result.append(nums2.pop(0))
        else:
            result.append(nums1.pop(0))

    print(result)
    if len(index) == 1:
        print(result[-1])
    else:
        print(result[-1] / 2 + result[-2] / 2)
复制代码

 

posted @   我不知道取什么名字好  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
点击右上角即可分享
微信分享提示