审题!审题!审题!重要的事情说三遍。
看到题目是不是觉得好像很熟悉的样子?然后一不小心就手撸了个归并排序?没错,我就是这样的。
这题感觉应该算是一个插入排序,或者说把Nums2加入到Nums1的队尾然后进行排序。
不过我既然已经把归并排序xiew写完了,那么肯定不会再用投机取巧的方法,算是给自己一个教训把:
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
resu = []
st1 = 0
st2 = 0
for i in range(m + n):
if st2 == n or st1 < m and nums1[st1] < nums2[st2]:
resu.append(nums1[st1])
st1 += 1
else:
resu.append(nums2[st2])
st2 += 1
for i in range(m+n):
nums1[i] = resu[i]