思想:
从nums1和nums2末尾的元素开始比较大小,大的则留在nums1[end]。
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.
"""
end = m+n-1
m = m-1
n = n-1
if m == -1:
nums1[0] = nums2[0]
while end >= 0 and m >= 0 and n >= 0:
if nums1[m] > nums2[n]:
nums1[end] = nums1[m]
m = m-1
else:
nums1[end] = nums2[n]
n = n - 1
end = end-1
while n >= 0:
nums1[end] = nums2[n]
n = n-1
end = end-1
之前我比较喜欢用for循环套用,有的时候数组下标变换并不是连续的,这是我借鉴大佬的while,感觉很好用。
比较大小一般也是喜欢从头开始,这种题从末尾开始确是简单不少。