https://leetcode.com/problems/merge-sorted-array/
一个从前还是从后计算的问题,对于inplace的问题,有时候需要考虑,这个就是一个简单的示范。
个人解答
class Solution:
def merge(self, n1: List[int], m: int, n2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
i, j = m - 1, n - 1
k = m + n - 1
while k >= 0:
# print(i, j, k)
if j < 0:
n1[k] = n1[i]
i -= 1
elif i < 0:
n1[k] = n2[j]
j -= 1
else:
if n1[i] >= n2[j]:
n1[k] = n1[i]
i -= 1
else:
n1[k] = n2[j]
j -= 1
k -= 1
题目分析
没有什么好分析的,两点:
- in-place,考虑从后向前来更改数组
- 注意边界条件