LeetCode热题100-88. 合并两个有序数组

这个题不在hot-100

给你两个按 非递减顺序 排列的整数数组 nums1nums2,另有两个整数 mn ,分别表示 nums1nums2 中的元素数目。

请你 合并 nums2nums1 中,使合并后的数组同样按 非递减顺序 排列。

注意: 最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n

首先想到的就是合并后排序就OK,时间复杂度为O(m+n)log(m+n).

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.
        """
        l = m
        for i in range(len(nums2)):
            nums1[l] = nums2[i]
            l += 1
        nums1.sort()
        

第二种依赖数组有序,可以使用三针指的方法。时间复杂度O(m + n)

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.
        """
        i = m - 1
        j = n - 1
        k = m + n -1

        while i >= 0 and j >= 0:
            if nums1[i] > nums2[j]:
                nums1[k] = nums1[i]
                i -= 1
            else:
                nums1[k] = nums2[j]
                j -= 1
            k -= 1
        while j >= 0:
            nums1[k] = nums2[j]
            j -= 1
            k -= 1
相关推荐
CSDN_RTKLIB30 分钟前
树、图高层抽象模型
算法
Dola_Zou8 小时前
工厂智能排产软件算法保护与按产线计费实战
算法·自动化·软件工程·软件加密
啦啦啦啦啦zzzz10 小时前
Logger的组装(c++20)
c++·算法·c++20
尾善爱看海11 小时前
前端算法与手写题集
前端·算法
程序员阿鹏11 小时前
为什么MySQL InnoDB选择B+树?
数据结构·数据库·b树·sql·mysql·算法·缓存
AI 思录11 小时前
Prompt 事故档案(八):日常表达被标为“待校准”,AI 的爹味语法从哪里来
大数据·人工智能·算法·prompt·用户体验·ai合规
月光船幽幽12 小时前
跨范式映射的稳定接口设计
人工智能·python·算法
2601_9657422213 小时前
全媒体运营与短视频代运营,两者有什么区别?
大数据·数据结构·人工智能·算法·ai·媒体
wordbaby14 小时前
混合检索:两全其美的艺术
人工智能·算法