1.1 面试经典 150 题-合并两个有序数组

合并两个有序数组

方法一:先合并再排序

python 复制代码
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

        # 先合并
        for i in range(m, m+n):
            nums1[i] = nums2[i - m]

        # 再排序
        nums1.sort()

方法二:从尾部按序插入表

python 复制代码
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        pos_1, pos_2 = m, n
        count = 0
        while pos_1 > 0 and pos_2 > 0:
            # 从nums1的末尾开始填入数字
            pos = m + n - count - 1
            if nums1[pos_1 - 1] <= nums2[pos_2 - 1]:
                # 最大值出现在nums2的指针处,将值填入,并将pos2指针向前偏移
                nums1[pos] = nums2[pos_2 - 1]
                pos_2 -= 1
            else:
                # 最大值出现在nums1的指针处,将值填入,并将pos2指针向前偏移
                nums1[pos] = nums1[pos_1 - 1]
                pos_1 -= 1
            # 已填入的个数+1
            count += 1
        if not pos_1:
            # nums2中还有数据没有填入
            nums1[:pos_2] = nums2[:pos_2]
相关推荐
Sakura_j_h_20 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
QuZhengRong20 小时前
【AI】Agent 全栈进阶|AgentScope 沙箱源码解析
python·学习·ai·agent·沙箱
Eider199821 小时前
Python基础语法之并发相关3
开发语言·python
M--Y1 天前
LangGraph 架构基石:持久化与运行控制
python·langchain·大模型·llm·持久化·langgraph
用户019027581611 天前
新浪财经 / 东方财富股票接口不稳、被限?稳定替代方案
python
七夜zippoe1 天前
Nexent 知识库:调优靠 Chunk 与重排
开发语言·python·ai智能体·nexent·知识库与rag
承渊政道1 天前
【Python编程—从入门到实践】(用户账户:给Django网站装上登录系统,让每个人拥有自己的学习笔记)
python·学习·pycharm·django
承渊政道1 天前
【Python编程—从入门到实践】(设置样式并部署:给Django网站换新装,把学习笔记发布到互联网)
python·学习·pycharm·django
用户298698530141 天前
使用 Python 将 JSON 转换为 Word 文档的实践指南
python·json·api
卷无止境1 天前
AI 加速开发之后,如何应对尚未发现的代码安全威胁
后端·python