双指针
May 2, 2024Less than 1 minute
虽然是个简单题, 但这个双指针做法确实有难度
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.
"""
ptr_1 = m - 1
ptr_2 = -1
for i in range(-1, -m - n - 1, -1):
if ptr_1 >= 0 and ptr_2 > -n - 1:
if nums1[ptr_1] > nums2[ptr_2]:
nums1[i] = nums1[ptr_1]
ptr_1 -= 1
else:
nums1[i] = nums2[ptr_2]
ptr_2 -= 1
elif ptr_1 >= 0:
nums1[i] = nums1[ptr_1]
ptr_1 -= 1
elif ptr_2 > -n - 1:
nums1[i] = nums2[ptr_2]
ptr_2 -= 1
return