【发布时间】:2020-06-13 22:01:07
【问题描述】:
我已经成功解决了 Leetcode 上的第 88 题,可以在这里找到:https://leetcode.com/problems/merge-sorted-array/
问题要求我们按升序将列表 nums2 就地合并到列表 nums1 中。
我正在尝试简化我的代码(如下)。我已经从我的原始解决方案中注释掉了代码的最后一部分(正常工作)。在此之上,我添加了一个“if c2
我的新解决方案的错误输出:
[2,5,2,3,0,0,0]
正确的输出是:
[1,2,2,3,5,6]
输入:
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3,其中m和n分别是nums1和nums2的长度.
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
if not nums2:
return
c1 = 0
c2 = 0
while m > c1 and n > c2:
if nums2[c2] <= nums1[c1]:
nums1.insert(c1, nums2[c2])
c2 += 1
c1 += 1
m += 1
else:
c1 += 1
if c2 == n:
del nums1[m:]
return
# New code to add end of nums2 to end of nums1
if c2 < n:
nums1[:n-c2] = nums2[:n-c2]
# Old code to add end of nums2 to end of nums1
# while c2 < n:
# nums1[c1] = nums2[c2]
# c2 += 1
# c1 += 1
# delete trailing 0s
# del nums1[c1:]
对不起,如果我的代码很丑,我是编程新手。
【问题讨论】:
-
输入为:
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5], n = 2