{ "type": "code_options", "author": "https://github.com/qiyuangong/leetcode", "source": "solution.md", "exercise_id": "6ac5ec62fe274644980c8fbc4bcb5612", "keywords": "数组,双指针,排序", "title": "合并两个有序数组", "desc": [ { "content": "\n

给你两个有序整数数组 nums1 nums2,请你将 nums2 合并到 nums1 使 nums1 成为一个有序数组。

初始化 nums1nums2 的元素数量分别为 mn 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nums2 的元素。

 

示例 1:

输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
输出:
[1,2,2,3,5,6]

示例 2:

输入:nums1 = [1], m = 1, nums2 = [], n = 0
输出:
[1]

 

提示:

", "language": "markdown" } ], "answer": [ { "content": "", "language": "python" } ], "prepared": [ [ { "content": "", "language": "python" } ], [ { "content": "", "language": "python" } ], [ { "content": "", "language": "python" } ] ], "template": { "content": "class Solution(object):\n\tdef merge(self, nums1, m, nums2, n):\n\t\t\"\"\"\n\t\t:type nums1: List[int]\n\t\t:type m: int\n\t\t:type nums2: List[int]\n\t\t:type n: int\n\t\t:rtype: void Do not return anything, modify nums1 in-place instead.\n\t\t\"\"\"\n\t\tp1, p2 = m - 1, n - 1\n\t\tpos = m + n - 1\n\t\twhile p1 >= 0 and p2 >= 0:\n\t\t\tif nums1[p1] >= nums2[p2]:\n\t\t\t\tnums1[pos] = nums1[p1]\n\t\t\t\tp1 -= 1\n\t\t\telse:\n\t\t\t\tnums1[pos] = nums2[p2]\n\t\t\t\tp2 -= 1\n\t\t\tpos -= 1\n\t\twhile p2 >= 0:\n\t\t\tnums1[pos] = nums2[p2]\n\t\t\tp2 -= 1\n\t\t\tpos -= 1\n\t\treturn nums1\n# %%\ns = Solution()\nprint(s.merge(nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3))", "language": "python" }, "node_id": "dailycode-8c71087921b345cd8aceed9913f3cea3", "license": "csdn.net", "created_at": 1637894161, "topic_link": "https://bbs.csdn.net/topics/600470926" }