【Leetcode】寻找两个正序数组的中位数 @ systemime | 2022-01-27T18:49:03+08:00 | 2 分钟阅读 | 更新于 2022-01-27T18:49:03+08:00

描述

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

示例 3:

输入:nums1 = [0,0], nums2 = [0,0]
输出:0.00000

示例 4:

输入:nums1 = [], nums2 = [1]
输出:1.00000

示例 5:

输入:nums1 = [2], nums2 = []
输出:2.00000

提示:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106

Related Topics

  • 数组
  • 二分查找
  • 分治

👍 4921
👎 0

题解

python

先来偷个懒,排序用python内置排序

"""
6:52 PM	info
		解答成功:
		执行耗时:32 ms,击败了92.13% 的Python用户
		内存消耗:13.1 MB,击败了77.32% 的Python用户
"""

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):

        nums = nums1 + nums2
        nums.sort()
        ss = len(nums) // 2
        ee = len(nums) % 2

        if ee:
            return nums[ss]
        
        # {:.5f}.format(restule)
        # Decimal(restule).quantize(Decimal("0.00"))
        # 这里题目虽然后面跟小数点了但是实际返回不要求,但是必须是浮点型
        return float((nums[ss-1] + nums[ss])) / 2

偷的懒必须加回来,因为是两个有序的数组,自己实现一下归并排序吧(此时快排时间复杂度由nlog2n变成了n2,实际测试1k+ms,就不贴了)

"""归并
7:02 PM	info
		解答成功:
		执行耗时:40 ms,击败了62.20% 的Python用户
		内存消耗:13.1 MB,击败了86.29% 的Python用户
"""

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):

        l_index, r_index, merger = 0, 0, []
        while l_index < len(nums1) and r_index < len(nums2):
            if nums1[l_index] <= nums2[r_index]:
                merger.append(nums1[l_index])
                l_index += 1
            else:
                merger.append(nums2[r_index])
                r_index += 1
        merger = merger + nums1[l_index:] + nums2[r_index:]

        ss = len(merger) // 2
        ee = len(merger) % 2

        if ee:
            return merger[ss]
        return float((merger[ss-1] + merger[ss])) / 2

© 2018 - 2022 systemime 的博客

Powered by Hugo with theme Dream.

---

avatar
关于我

systemime 的博客

记录一些生活与技术的事或思考

毕业于 🏫 山东科技大学泰山科技学院

目前职位为Python后端开发工程师

热爱代码,热爱开源

主要的技术栈是:

  • python
  • celery
  • django
  • shell
  • sql
  • go
  • nginx

爱好

  • 羽毛球
  • 编码
我的一些开源项目

计划或项目:

  • skill_test ➡️ 一个包含项目常用的django模板:常用脚本、单测方法、数据库连接池、异步请求池,restful风格的回调接口管理器 60%
  • Vbox ➡️ 一个基于k8s和docker的容器云平台,早期项目代码较简单 90%
  • YuQue-Assistant ➡️ 用于批量拉取语雀工作区文章,使用进程池+协程
  • 一个代理池 60%
  • simple_db_pool ➡️ 一个简单数据库连接池 100%
  • 一个电报消息转发脚本 90%
  • 使用flutter做一个app 计划中
  • 其他若干脚本(bilibili、微博图片视频下载、文件对比、图片颜色提取…)
其他

如果你喜欢我的博客、开源项目或者它们可以给你带来帮助,可以赏一杯咖啡 ☕ 给我。~

If you like my open source projects or they can help you. You can buy me a coffee ☕.~

PayPal

https://paypal.me/systemime

支付宝赞赏码

alipay

微信赞赏码

wechat

最好附加一下信息或者留言,方便我可以将捐助记录 📝 下来,十分感谢 🙏。

It is better to attach some information or leave a message so that I can record the donation 📝, thank you very much 🙏.