题目:
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
- 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
- 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6]
思路:首先想到的思路是先从前向后找到位置,然后插入进去,这样可能需要将一些元素往后挪动一些位置,时间复杂度o(n*n),但是记住遇到这种排好序的数组操作,时间复杂度一般为o(n),所以我们再仔细观察题目,发现nums1末尾的数字都相当于未定。如果从后向前查找位置,不就不需要挪动了嘛,只需要交换。
代码:
从前向后:
class Solution:
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.
"""
len1 = m
len2 = n
#num1最后一个有效的数字
lent = m -1
index1 = 0
index2 = 0
if n != 0:
while index1 < m+n and index2 < len2:
#如果num1大于num2,则将num2插入num1中
if nums1[index1] > nums2[index2]:
i = lent
while i >= index1:
nums1[i+1] = nums1[i]
i -= 1
nums1[index1] = nums2[index2]
index2 += 1
lent += 1
#判断剩余需要合并的num2都大于num1的元素
elif nums2[index2] >= nums1[lent]:
nums1[lent+1] = nums2[index2]
index2 += 1
lent += 1
index1 = lent -1
index1 += 1
从后向前:先把末尾的空位置填满,如果遍历完num2,则说明完成,如果没有遍历完num2就遍历完num1了,则需要将num2的元素填充到num1前面去
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.
"""
if n !=0:
index1 = m -1
index2 = n-1
lent = m + n - 1
while index1 >=0 and index2 >= 0:
if nums1[index1] > nums2[index2]:
nums1[lent] = nums1[index1]
index1 -= 1
lent -= 1
else:
nums1[lent] = nums2[index2]
index2 -= 1
lent -= 1
while index2 >= 0:
nums1[lent] = nums2[index2]
index2 -= 1;lent -= 1