给定两个有序整数数组nums1和nums2,合并nums1和nums2为数组nums1,
注意:
数组nums1和nums2初始化元素个数分别为m和n
假设num1有足够空间(长度超过m+n或与其相等)保存nums2中所有的元素
Example:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
1:正序遍历nums2,按从小到大的顺序插入nums1中
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
count = 0 #nums2索引
index = 0 #nums1索引
while count<n: #判断条件(nums2长度)
if nums1[index]>nums2[count]: #nums2中元素插入nums1中有效部分(非0部分)
# for i in range(m+count,index,-1): #注释的两行和注释下面一行效果相同
# nums1[i] = nums1[i-1]
nums1[index+1:m+count+1] = nums1[index:m+count]
nums1[index] = nums2[count]
count += 1
if index > m+count-1: #nums2中元素插入nums1列表后面全0区域
nums1[index] = nums2[count]
count += 1
index += 1
2:利用str.sort()方法
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
nums1[m:m+n] = nums2
return nums1.sort()
3:倒序遍历nums1和nums2,按从大到小的顺序插入sum1中
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while n>0 and m>0:
if nums2[n-1]>nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else:
nums1[m+n-1] = nums1[m-1]
m -= 1
if n>0:
nums1[:n] = nums2[:n]
算法题来自:https://leetcode-cn.com/problems/merge-sorted-array/description/