1.题目描述
2.代码构思(debug)
方法1: 先合并两个数组,然后排序
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()
方法2:双指针法,从两个数组第一位开始逐个元素比较
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.
"""
if m <= 0 and n <= 0:
return
if m <=0:
if n == 1:
nums1[0] = nums2[0]
for i in range(n):
nums1[i] = nums2[i]
if n <= 0:
return nums1
count1 = 0
count2 = 0
lst = []
while count1 < m and count2 < n:
if nums1[count1] < nums2[count2]:
lst.append(nums1[count1])
count1 += 1
else:
lst.append(nums2[count2])
count2 += 1
if count1 < m:
lst = lst + nums1[count1:m]
if count2 < n:
lst = lst + nums2[count2:n]
for i in range(len(lst)):
nums1[i] = lst[i]