概述
用暴力的方法很简单,非暴力的解法比较巧妙
合并后排序
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,0
while j<n:
nums1[i] = nums2[j]
i += 1
j += 1
nums1.sort()
双指针 使用额外空间
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 = 0,0
lst = []
while i<m and j<n:
if nums1[i] <= nums2[j]:
lst.append(nums1[i])
i += 1
else:
lst.append(nums2[j])
j += 1
while i<m:
lst.append(nums1[i])
i += 1
while j<n:
lst.append(nums2[j])
j += 1
nums1[:] = lst
双指针 不使用额外空间
这个着实没想出来
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.
"""
p1, p2 = m - 1, n - 1
tail = m + n - 1
while p1 >= 0 or p2 >= 0:
if p1 == -1:
nums1[tail] = nums2[p2]
p2 -= 1
elif p2 == -1:
nums1[tail] = nums1[p1]
p1 -= 1
elif nums1[p1] > nums2[p2]:
nums1[tail] = nums1[p1]
p1 -= 1
else:
nums1[tail] = nums2[p2]
p2 -= 1
tail -= 1
就是从后往前遍历,每次把较大的元素放到尾部