Sol 1:
python
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums1[m:] = nums2
nums1.sort()
return nums1
copy nums2 then sort
python
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
i, j = m - 1, n - 1
p = m + n - 1
while j >= 0: # ! nums2 还有要合并的元素
# 如果 p1 < 0,那么走 else 分支,把 nums2 合并到 nums1 中
if i >= 0 and nums1[i] > nums2[j]: # i >= 0 and
nums1[p] = nums1[i]
i -= 1
else:
nums1[p] = nums2[j]
j -= 1
p -= 1
return nums1
NOTE:
while j >= 0:
Here j is the index of nums2. How to decide the stop conditions is important. Because we must make sure all nums2's elements be moved into nums1. So here we use the index of nums2 as condition.
if i >= 0 and nums1[i] > nums2[j]:
if we do not have this i >= 0 then index out of range. Beside if all elements in nums1 has been moved then we must move the nums2's elements. Merge nums2 into nums1.