一、原题
给你两个有序整数数组
nums1 和
nums2,请你将
nums2 合并到
nums1 中
,使
nums1 成为一个有序数组。
二、思路
解法一:归并排序
这种解法运用到了归并排序的思想:使用双指针同时遍历两个数组,比较指针指向元素的大小,将小的元素放到正确的位置即可。
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 = 0
j = 0
index = 0
tmp = nums1.copy()
while(i < m and j < n):
if(tmp[i] <= nums2[j]):
nums1[index] = tmp[i]
i += 1
index += 1
else:
nums1[index] = nums2[j]
j += 1
index += 1
while(i<m):
nums1[index] = tmp[i]
index += 1
i += 1
while(j < n):
nums1[index] = nums2[j]
index += 1
j += 1
时间复杂度为O(m+n),空间复杂度为O(m)
在上述代码中 ,有一行代码需要注意,即tmp = nums1.copy(), 看如下代码:
nums = [1,2,3,0,0,0]
print(id(nums)) # 2927496620680
# 方式一
tmp = nums
print(tmp) # [1, 2, 3, 0, 0, 0]
print(id(tmp)) # 2927496620680
# 方式二
tmp1 = nums.copy()
print(tmp1) # [1, 2, 3, 0, 0, 0]
print(id(tmp1)) # 2927496550920
# 方式三
tmp2 = nums[:]
print(tmp2) # [1, 2, 3, 0, 0, 0]
print(id(tmp2)) # 2927496551048
可以发现,三种方式下,数组tmp、tmp1、tmp2中的值都是一样的,但是在方式一的情况下,tmp和nums的id是一样的,也就是两个变量指向内存当中同一块地址;而在方式二和三的情况下,tmp2和tmp3只是和nums中的值一致,id是不一样的,即这三个变量分别指向不同的内存地址。那么指向同一内存地址会有什么影响呢?此时,如果我们改变tmp中元素的值,如tmp[1] = 20,则会发现nums[1]的值变为20。而若我们改变tmp1和tmp2的值,则不会影响nums中的值,因为这三个变量指向不同的内存单元。
对比方式一和方式三,我们发现python中nums 与nums[:] 的不同,nums[:]等价于nums[0, len(nums)],只是将数组中的值赋给等号右边的变量;而tmp = nums的方式,我们可以理解为每一个内存地址都会有变量名字与之对应,这个对应关系是一对多的,即2927496620680这个地址开始有个变量名为nums,而tmp = nums则是给这个地址又起了一个新的名字tmp。
原题中要求我们直接在num1上改动,因此我们申请的临时变量tmp只能用方式二或者方式三的方式赋值,若用方式一,会产生错误答案。
解法二:运用sorted
只需要将nums1的前m个元素和nums2的n个元素组成一个新的数组,然后直接排序。
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
nums1[:] = sorted(nums1[:m] + nums2)
算法的时间复杂度为O((n+m)(log(n+m))),空间复杂度为O(1)
解法三:从后往前遍历
解法一中已经达到了最好的时间复杂度,我们考虑有没有办法进一步降低空间复杂度?之所以需要O(m)的空间复杂度,是因为我们从前往后遍历两个数组,每次取出较小的值放于nums1中,因此我们需要提前将nums1中的元素保存下来。那么,如果是从后往前遍历,每次取出较大的值呢?代码如下
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 = m-1
j = n-1
index = m+n-1
while(i >=0 and j >=0):
if(nums1[i] <= nums2[j]):
nums1[index] = nums2[j]
j -= 1
index -= 1
else:
nums1[index] = nums1[i]
i -= 1
index -= 1
nums1[: j+1] = nums2[:j+1]
此时,算法的时间复杂度为O(m+n),空间复杂度为O(1)。