题目:
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
标准答案:
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.
"""
k = m + n - 1 # 目标数组总长度
while m > 0 and n > 0: # 只要两个数组任意一个遍历完
if nums1[m - 1] > nums2[n - 1]: # 一数组最后一个比二最后一个大
nums1[k] = nums1[m - 1] # 将一数组最后一个移到目标数组最后一个
m -= 1 # 一数组的指针左移
else:
nums1[k] = nums2[n - 1] # 将二数组最后一个移到目标数组最后一个
n -= 1 # 将二数组的指针左移
k -= 1 # 目标数组指针左移
nums1[:n] = nums2[:n] # 如果第二个数组未遍历完,说明一数组已排序好,将二数组剪切过来
本人的绝佳烂代码😂😂😂🤣🤣🤣:
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 = nums1
_nums2 = nums2
if m == 0:
nums1[0:m + n] = nums2
return
elif n == 0:
return
elif m > 0 and n > 0:
_index = 0
_value1 = nums1[0]
print(_nums2)
# 每遍历到一个数据时,则必须要插入到nums1中。
for count, _value2 in enumerate(_nums2):
print("_value1:", _value1, "_value2:", _value2)
if _value2 <= _value1:
if _index == m + n - 1:
nums1[_index] = _value2
return
elif _index < m + n - 1:
nums1[_index + 1:] = nums1[_index:-1]
nums1[_index] = _value2
print("nums1[", _index, "]:", nums1[_index], nums1)
# 自己的索引,包括m+n:此处插入了value2,因此+1
_index += 1
elif _value2 > _value1:
_index += 1
# 此时nums1中已有元素已经遍历完毕,剩下nums2元素都比nums1大,直接元素赋值
if _index == m + count:
nums1[m + count:] = nums2[count:]
break
elif _index < m + count:
_value1 = nums1[_index]
print("[second]value1:", _value1, "_value2:", _value2)
# 移动nums1中元素
while _value2 > _value1 and _index < m + count:
_index += 1
# 遍历nums1,直到value2<=value1,此时value2可以插入
_value1 = nums1[_index]
print("[third]_value1:", _value1, "_value2:", _value2, "_index:", _index)
if _index == m + count:
nums1[m + count:] = nums2[count:]
break
elif _value2 <= _value1:
nums1[_index + 1:] = nums1[_index:-1]
nums1[_index] = _value2
print("nums1[", _index, "]=", nums1[_index], ",", nums1, "nums1:", nums1)
# 自己的索引,包括m+n
_index += 1
反思:
1、列表赋值不能简单的使用=:对于一个函数外的列表,如果直接在函数中使用=赋值,函数外依然不变。
2、列表的索引和长度经常混淆:对于不为空的列表,索引从0开始,长度从1开始。编程时最好长度和索引区分,比如长度直接使用m、n,索引就使用k或者index之类的变量,以示区分。
3、该题有几个隐藏条件:需要充分使用有序以及nums1已经填充的n个0。
网友评论