Leetcode 88. Merge Sorted Array

Question

Solution

逆向考虑,如果nums2的最后一位大于nums1的最后一位,则复制。如果小于,则nums1的前一位复制到当前。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.
"""
l1, l2, end = m-1, n-1, m+n-1
while l1 >= 0 and l2 >= 0:
if nums2[l2] > nums1[l1]:
nums1[end] = nums2[l2]
l2 -= 1
else:
nums1[end] = nums1[l1]
l1 -= 1
end -= 1

if l1 < 0:
nums1[:l2+1] = nums2[:l2+1]