寻找两个正序数组的中位数 - 困难

news2025/5/16 12:37:24

*************

Python

topic: 4. 寻找两个正序数组的中位数 - 力扣(LeetCode)

*************

Give the topic an inspection.

Do the old topic will give you some new sparks. Before that, I do some really good craetive things about my logo. It will used at the very begin at my travel vlog. I am excited to do this little things. Maybe one shoot in my vedio costs me some time to figure it out. Recording makes me feel real in my life. I think the most time of my year is without ripples. But some moments light the boring days. I wil never forget the day I stood at the 5276 meters altitude. Nor will I forget the day I saw so many fish swimming next to me at the bottom of the sea. I love that moments. I am about to plan my travel to Xinjiang next mounth. I am so excited about the commoing travel.

Back to the topic, the first thing is to merge the two list.

1、merge the two lists

the basic usage of adding element in the end of the list is very easy.

nums = [1, 2, 3]

# append只能加一个
nums.append(4)       # 输出: [1, 2, 3, 4]

# extend可以加一串
nums.extend([4, 5])  # 输出: [1, 2, 3, 4, 4, 5]

and in the program I can use both of them.

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        merged = [] #创建一个新的list,并初始化为空
        i = 0
        j = 0

        #开始合并两个list
        if nums1[i] < nums2[j]:
            merged.append(nums1[i])
            i = i + 1
        else:
            merged.append(nums2[j])
            j = j + 1
        
        # 将剩下的元素添加到merged中
        merged.extend(nums1[i:]) #   : 表示从i到末尾的elements
        merged.extend(nums2[j:])
            

Then find the one right in the middle of the line.

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        merged = [] #创建一个新的list,并初始化为空
        i = 0
        j = 0

        #开始合并两个list
        if nums1[i] < nums2[j]:
            merged.append(nums1[i])
            i = i + 1
        else:
            merged.append(nums2[j])
            j = j + 1
        
        # 将剩下的元素添加到merged中
        merged.extend(nums1[i:]) #   : 表示从i到末尾的elements
        merged.extend(nums2[j:])
            
        # 找到中间那个
        length = len(merged)
        if length % 2 == 1:
            return merged[length // 2] # //是整数除法的意思
        else:
            return (merged[length // 2 - 1] + merged[length // 2]) / 2.0

something wrong as usual.

ai tell me that line 22 went wrong. add the loop.

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        merged = [] #创建一个新的list,并初始化为空
        i = 0
        j = 0

        #开始合并两个list
        while i < len(nums1) and j < len(nums2):
            if nums1[i] < nums2[j]:
                merged.append(nums1[i])
                i = i + 1
            else:
                merged.append(nums2[j])
                j = j + 1
        
        # 将剩下的元素添加到merged中
        merged.extend(nums1[i:]) #   : 表示从i到末尾的elements
        merged.extend(nums2[j:])
            
        # 找到中间那个
        length = len(merged)
        if length % 2 == 1:
            return merged[length // 2] # //是整数除法的意思
        else:
            return (merged[length // 2 - 1] + merged[length // 2]) / 2.0

this code works well, but . If you notice that, you will ask what is time complexity.

iterate through the array: i = 0 -> n  O(n)

嵌套i次: O(n的几次方)

二分查找:O(log n)

so this topic tell you that you have to use the dichotomy to solve the problem. Make sure that the shorter one stands ahead.

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        # 短的数组要在前面
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2. nums1
        
        # 初始化两个指针,用于二分法查找
        m          = len(nums1)
        n          = len(nums2)
        left       = 0
        right      = m
        total_left = (m + n + 1) / 2

Then make pointer i and point j stand just at the middle of the line. pointer i is kind of knife, i cuts the whole array which tears the array apart.

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        # 短的数组要在前面
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2. nums1
        
        # 初始化两个指针,用于二分法查找
        m          = len(nums1)
        n          = len(nums2)
        left       = 0
        right      = m
        total_left = (m + n + 1) / 2

        # 让两个指针先到中间站着位置
        while left <= right:
            i = (left + right) // 2 
            j = total_left - i

        # 处理边界问题

i = (left + right) // 2, pointer i could be land in nums1, also could be land in nums2.

i 是 nums1 左边部分的长度,j 是 nums2 左边部分的长度。

如果 nums2_left > nums1_right,说明 nums2 的左边太大,需减少 j(即增大 i)。

如果 nums1_left > nums2_right,说明 nums1 的左边太大,需减少 i

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        # 短的数组要在前面
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1
        
        # 初始化两个指针,用于二分法查找
        m          = len(nums1)
        n          = len(nums2)
        left       = 0
        right      = m
        total_left = (m + n + 1) / 2 # 中位数左边应该有的元素个数

        # 让两个指针先到中间站着位置
        while left <= right:
            i = (left + right) // 2 
            j = total_left - i

        # 处理边界问题
         # 处理边界:当 i=0 时,nums1_left 无元素,设为 -∞;i=m 时,nums1_right 无元素,设为 +∞
            nums1_left = -float('inf') if i == 0 else nums1[i-1]
            nums1_right = float('inf') if i == m else nums1[i]
            
            # 同理处理 nums2 的边界
            nums2_left = -float('inf') if j == 0 else nums2[j-1]
            nums2_right = float('inf') if j == n else nums2[j]
class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        # 短的数组要在前面
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1
        
        # 初始化两个指针,用于二分法查找
        m          = len(nums1)
        n          = len(nums2)
        left       = 0
        right      = m
        total_left = (m + n + 1) / 2 # 中位数左边应该有的元素个数

        # 让两个指针先到中间站着位置
        while left <= right:
            i = (left + right) // 2 
            j = total_left - i

        # 处理边界问题
         # 处理边界:当 i=0 时,nums1_left 无元素,设为 -∞;i=m 时,nums1_right 无元素,设为 +∞
            nums1_left = -float('inf') if i == 0 else nums1[i-1]
            nums1_right = float('inf') if i == m else nums1[i]
            
            # 同理处理 nums2 的边界
            nums2_left = -float('inf') if j == 0 else nums2[j-1]
            nums2_right = float('inf') if j == n else nums2[j]

            # 检查分割条件
            if nums1_left <= nums2_right and nums2_left <= nums1_right:
                if (m + n) % 2 == 1:
                    return max(nums1_left, nums2_left)
                else:
                    return (max(nums1_left, nums2_left) + min(nums1_right, nums2_right)) / 2.0
            elif nums1_left > nums2_right:
                right = i - 1
            else:
                left = i + 1

举个例子:

  • nums1 = [1](长度 m = 1
  • nums2 = [2, 3, 4, 5, 6, 7, 8, 9](长度 n = 8
1. 初始化变量
  • m = 1nums1 的长度)
  • n = 8nums2 的长度)
  • total_left = (1 + 8 + 1) // 2 = 5(中位数左边应有 5 个元素)
  • 二分查找范围:left = 0right = m = 1
2. 二分查找过程

第一次迭代

  • i = (left + right) // 2 = (0 + 1) // 2 = 0
  • j = total_left-i = 5-0 = 5

分割结果

  • nums1 的分割点 i = 0
    • 左边:[]nums1_left = -∞
    • 右边:[1]nums1_right = 1
  • nums2 的分割点 j = 5
    • 左边:[2, 3, 4, 5, 6]nums2_left = 6
    • 右边:[7, 8, 9]nums2_right = 7

检查分割条件

  1. nums1_left <= nums2_right → -∞ <= 7 ✅
  2. nums2_left <= nums1_right → 6 <= 1 ❌

调整二分范围
由于 nums2_left > nums1_right6 > 1),说明 nums2 的左边部分太大,需要减少 nums2 的左边元素数量。
因此,增大 i (让 nums1 贡献更多左边元素,从而减少 nums2 的左边元素):
left = i + 1 = 1

第二次迭代

  • i = (1 + 1) // 2 = 1
  • j = 5-1 = 4

分割结果

  • nums1 的分割点 i = 1
    • 左边:[1]nums1_left = 1
    • 右边:[]nums1_right = +∞
  • nums2 的分割点 j = 4
    • 左边:[2, 3, 4, 5]nums2_left = 5
    • 右边:[6, 7, 8, 9]nums2_right = 6

检查分割条件

  1. nums1_left <= nums2_right → 1 <= 6 ✅
  2. nums2_left <= nums1_right → 5 <= +∞ ✅

分割合法!此时:

  • 左边部分:[1] + [2, 3, 4, 5](共 5 个元素)
  • 右边部分:[] + [6, 7, 8, 9](共 4 个元素)
3. 计算中位数
  • 总长度 m + n = 9(奇数),中位数是左边部分的最大值:
    max(nums1_left, nums2_left) = max(1, 5) = 5

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2376847.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

国产密码新时代!华测国密 SSL 证书解锁安全新高度

在数字安全被提升到国家战略高度的今天&#xff0c;国产密码算法成为筑牢网络安全防线的关键力量。华测国密SSL证书凭借其强大性能与贴心服务&#xff0c;为企业网络安全保驾护航&#xff0c;成为符合国家安全要求的不二之选&#xff01;​ 智能兼容&#xff0c;告别浏览器适配…

【金仓数据库征文】从云计算到区块链:金仓数据库的颠覆性创新之路

目录 一、引言 二、金仓数据库概述 2.1 金仓数据库的背景 2.2 核心技术特点 2.3 行业应用案例 三、金仓数据库的产品优化提案 3.1 性能优化 3.1.1 查询优化 3.1.2 索引优化 3.1.3 缓存优化 3.2 可扩展性优化 3.2.1 水平扩展与分区设计 3.2.2 负载均衡与读写分离 …

股指期货套期保值怎么操作?

股指期货套期保值就是企业或投资者通过持有与其现货市场头寸相反的期货合约&#xff0c;来对冲价格风险的一种方式。换句话说&#xff0c;就是你在股票市场上买了股票&#xff08;现货&#xff09;&#xff0c;担心股价下跌会亏钱&#xff0c;于是就在期货市场上卖出相应的股指…

基于IBM BAW的Case Management进行项目管理示例

说明&#xff1a;使用IBM BAW的难点是如何充分利用其现有功能根据实际业务需要进行设计&#xff0c;本文是示例教程&#xff0c;因CASE Manager使用非常简单&#xff0c;这里重点是说明如何基于CASE Manager进行项目管理&#xff0c;重点在方案设计思路上&#xff0c;其中涉及的…

黑马k8s(七)

1.Pod介绍 查看版本&#xff1a; 查看类型,这里加s跟不加s没啥区别&#xff0c;可加可不加 2.Pod基本配置 3.镜像拉去策略 本地没有这个镜像&#xff0c;策略是Never&#xff0c;启动失败 查看拉去策略&#xff1a; 更改拉去策略&#xff1a; 4.启动命令 运行的是nginx、busv…

九、HQL DQL七大查询子句

作者&#xff1a;IvanCodes 日期&#xff1a;2025年5月15日 专栏&#xff1a;Hive教程 Apache Hive 的强大之处在于其类 SQL 的查询语言 HQL&#xff0c;它使得熟悉 SQL 的用户能够轻松地对存储在大规模分布式系统&#xff08;如 HDFS&#xff09;中的数据进行复杂的查询和分析…

RTSP 播放器技术探究:架构、挑战与落地实践

RTSP 播放器为什么至今无法被淘汰&#xff1f; 在实时视频传输领域&#xff0c;RTSP&#xff08;Real-Time Streaming Protocol&#xff09;作为最基础、最常见的协议之一&#xff0c;至今依然被广泛用于监控设备、IP Camera、视频服务器等设备中。然而&#xff0c;要构建一个稳…

实验5 DNS协议分析与测量

实验5 DNS协议分析与测量 1、实验目的 了解互联网的域名结构、域名系统DNS及其域名服务器的基本概念 熟悉DNS协议及其报文基本组成、DNS域名解析原理 掌握常用DNS测量工具dig使用方法和DNS测量的基本技术 2、实验环境 硬件要求&#xff1a;阿里云云主机ECS 一台。 软件要…

【鸿蒙开发】性能优化

语言层面的优化 使用明确的数据类型&#xff0c;避免使用模糊的数据类型&#xff0c;例如ESObject。 使用AOT模式 AOT就是提前编译&#xff0c;将字节码提前编译成机器码&#xff0c;这样可以充分优化&#xff0c;从而加快执行速度。 未启用AOT时&#xff0c;一边运行一边进…

2025-05-13 学习记录--Python-循环:while循环 + while-else循环 + for循环 + 循环控制

合抱之木&#xff0c;生于毫末&#xff1b;九层之台&#xff0c;起于累土&#xff1b;千里之行&#xff0c;始于足下。&#x1f4aa;&#x1f3fb; 一、循环 ⭐️ &#xff08;一&#xff09;、while循环 &#x1f36d; 初始条件设置 -- 通常是重复执行的 计数器while 条件(判…

Vue3学习(组合式API——生命周期函数基础)

目录 一、Vue3组合式API中的生命周期函数。 &#xff08;1&#xff09;各阶段生命周期涉及函数简单介绍。 <1>创建挂载阶段的生命周期函数。 <2>更新阶段的生命周期函数。 <3>卸载阶段的生命周期函数。 <4>错误处理的生命周期函数。 &#xff08;2&…

计量——检验与代理变量

1.非嵌套模型的检验 1Davidson-Mackinnon test 判断哪个模型好 log&#xff08;y&#xff09;β0β1x1β2x2β3x3u log&#xff08;y&#xff09;β0β1log&#xff08;x1&#xff09;β2log&#xff08;x2&#xff09;β3log&#xff08;x3&#xff09;u 1.对log&#xff…

HTML-实战之 百度百科(影视剧介绍)

本系列可作为前端学习系列的笔记&#xff0c;代码的运行环境是在HBuilder中&#xff0c;小编会将代码复制下来&#xff0c;大家复制下来就可以练习了&#xff0c;方便大家学习。 系列文章目录 HTML-1.1 文本字体样式-字体设置、分割线、段落标签、段内回车以及特殊符号 HTML…

计算机视觉---目标追踪(Object Tracking)概览

一、核心定义与基础概念 1. 目标追踪的定义 定义&#xff1a;在视频序列或连续图像中&#xff0c;对一个或多个感兴趣目标&#xff08;如人、车辆、物体等&#xff09;的位置、运动轨迹进行持续估计的过程。核心任务&#xff1a;跨帧关联目标&#xff0c;解决“同一目标在不同…

Weblogic SSRF漏洞复现(CVE-2014-4210)【vulhub靶场】

漏洞概述&#xff1a; Weblogic中存在一个SSRF漏洞&#xff0c;利用该漏洞可以发送任意HTTP请求&#xff0c;进而攻击内网中redis、fastcgi等脆弱组件。 漏洞形成原因&#xff1a; WebLogic Server 的 UDDI 组件&#xff08;uddiexplorer.war&#xff09;中的 SearchPublicR…

AI大模型应用:17个实用场景解锁未来

任何新技术的普及都需要经历一段漫长的过程&#xff0c;人工智能大模型也不例外。 尽管某些行业的从业者已经开始将大模型融入日常工作&#xff0c;但其普及程度仍远未达到“人手必备”的地步。 那么&#xff0c;究竟是什么限制了它的广泛应用&#xff1f;普通人如何才能用好…

java17

1.常见API之BigDecimal 底层存储方式&#xff1a; 2.如何分辨过时代码&#xff1a; 有横线的代码表示该代码已过时 3.正则表达式之字符串匹配 注意&#xff1a;如果X不是单一字符&#xff0c;需要加[]中括号 注意&#xff1a;1.想要表达正则表达式里面的.需要\\. 2.想要表…

C++算法(22):二维数组参数传递,从内存模型到高效实践

引言 在C程序设计中&#xff0c;二维数组的参数传递是许多开发者面临的棘手问题。不同于一维数组的相对简单性&#xff0c;二维数组在内存结构、类型系统和参数传递机制上都存在独特特性。本文将深入探讨静态数组、动态数组以及STL容器三种实现方式&#xff0c;通过底层原理分…

Lightpanda开源浏览器:专为 AI 和自动化而设计的无界面浏览器

​一、软件介绍 文末提供程序和源码下载 Lightpanda开源浏览器&#xff1a;专为 AI 和自动化而设计的无界面浏览器&#xff1b; Javascript execution Javascript 执行Support of Web APIs (partial, WIP)支持 Web API&#xff08;部分、WIP&#xff09;Compatible with Pla…

技术文档不完善,如何促进知识传承

建立统一的技术文档规范、引入文档自动化工具、将文档写作融入开发流程、建设团队知识共享文化 是促进知识传承的关键策略。在其中&#xff0c;尤应重视建立统一的技术文档规范&#xff0c;通过标准化文档结构、命名、版本管理等方式&#xff0c;提升文档质量和可维护性&#x…