leetcode 88. merge two sorted lists,关于python list赋值,与引用

问题描述
  1. Merge Sorted Array
    You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
    Merge nums1 and nums2 into a single array sorted in non-decreasing order.
    The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
一个标准回答
class Solution(object):
    def merge(self, nums1, m, nums2, n):

      for j in range(n):
          nums1[m+j] = nums2[j]
      nums1.sort()


非常好理解。

我的一个错误回答
class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        nums1_temp = nums1[:m]
        print(nums1_temp)
        merge_unsort = nums1_temp+nums2
        print(merge_unsort)
        merge_unsort.sort()
        print(merge_unsort)
        nums1 = merge_unsort
        print(nums1)
        return nums1

这里有两个地方要注意,一是list.sort()和sorted(list)的区别。 前者没有返回值,会直接改变list本身的值。
二是list的赋值, 并不能通过=号直接给,=这里是一个引用的作用,nums1指向了Merge_unsort,并不是"The final sorted array should not be returned by the function, but instead be stored inside the array nums1". nums1本身的值必须改变。 所以如果把最后改成:

nums1[:] = merge_unsort

也是可以的。

如何确定是本身的值变了,还是引用变了呢

可以通过打印地址,id(list)来确定。

print(id(nums1))
nums1 = merge_unsort
print(id(merge_unsort))
print(id(nums1))

#output
139976362657504
139976362709232
139976362709232

可以看到nums1在=之后指向merge_unsort的地址了。

class Solution(object):
    def merge(self, nums1, m, nums2, n):
      print(id(nums1))
      for j in range(n):
          nums1[m+j] = nums2[j]
      nums1.sort()
      print(id(nums1))
# output
140265616881456
140265616881456

可以看到引用地址没有变化

总结
  • list.sort()并不返回值,返回NONE。 sorted(list)可以返回排序后的列表。
  • List1 = list2 并不会挨个元素赋值,只会是引用后者, list1本身地址所在的值不会变。
  • 两种方法,第一种存在nums1中没有任何额外的空间开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值