【问题标题】:leetcode 88 merged sorted array python3 slicing questionleetcode 88 合并排序数组 python3 切片问题
【发布时间】:2020-02-09 23:40:29
【问题描述】:

这是leetcode问题:

给定两个排序整数数组 nums1 和 nums2,将 nums2 合并为 nums1 作为一个排序数组。

注意:

nums1和nums2中初始化的元素个数分别为m和n。 您可以假设 nums1 有足够的空间(大小大于或等于 m + n)来容纳来自 nums2 的其他元素。 示例:

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

输出:[1,2,2,3,5,6]

https://leetcode.com/problems/merge-sorted-array/

我的问题是“蛮力1”和“蛮力2”中的“nums1”和“nums1[:]”有什么区别?

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.
        """

        nums1=sorted(nums1[0:m]+nums2[0:n])

        return nums1

return,这是不正确的。

Your input
[1,2,3,0,0,0]
3
[2,5,6]
3
Output
[1,2,3,0,0,0]
Expected
[1,2,2,3,5,6]

解决方案2,正确

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.
        """

        nums1[:]=sorted(nums1[0:m]+nums2[0:n])

        return nums1[:]


Your input
[1,2,3,0,0,0]
3
[2,5,6]
3
Output
[1,2,2,3,5,6]
Expected
[1,2,2,3,5,6]

【问题讨论】:

    标签: python-3.x list sorting slice


    【解决方案1】:

    您的代码,包括文档字符串:

        def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
           """
           Do not return anything, modify nums1 in-place instead.
           """
    
           nums1=sorted(nums1[0:m]+nums2[0:n])
    
           return nums1
    

    不确定“不返回任何东西”的哪一部分启发了你返回一些东西:-)

    显然,法官很好,不会介意您确实返回了某些东西,但它肯定会忽略您返回的任何东西。此外,使用nums1 = my_new_list_object,您只需将局部变量重新分配给新创建的列表对象,根本不会修改给定的列表对象。所以法官甚至无法判断你做了任何事情

    另一方面,使用nums1[:] = ...,您并没有分配给本地变量,而是分配给它引用的列表的内容。这样确实根据需要修改给定的列表对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 2021-07-30
      • 2014-08-22
      • 2015-08-25
      • 2021-06-22
      • 1970-01-01
      • 2021-01-25
      相关资源
      最近更新 更多