问题描述
- 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中没有任何额外的空间开销。