【问题标题】:Add end of one list to end of another list in Python - Leetcode在 Python 中将一个列表的末尾添加到另一个列表的末尾 - Leetcode
【发布时间】: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

标签: python list merge


【解决方案1】:

这是heapq.merge的解决方案:

from heapq import merge

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:        
        nums1[:] = merge(nums1[:m], nums2)

结果(来自 Leetcode 的截图):

【讨论】:

    【解决方案2】:

    试试这个:

    import numpy as np
    
    nums1 = [1,2,3,0,0,0]
    m = 3
    nums2 = [2,5,6]
    n = 3
    
    print("Input: ",nums1,nums2)
    
    nums1 = nums1[:m]
    nums2 = nums2[:n]
    
    print("Step 1: ", nums1, nums2)
    step2 = np.concatenate((nums1, nums2))
    
    print("Step 2:", step2)
    step3 = np.sort(step2)
    
    print("Step3: ", step3)
    

    输出是:

    Input:  [1, 2, 3, 0, 0, 0] [2, 5, 6]
    Step 1:  [1, 2, 3] [2, 5, 6]
    Step 2: [1 2 3 2 5 6]
    Step3:  [1 2 2 3 5 6]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多