1. 题目
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
示例请看:合并两个有序数组
2. 解题思路
为什么倒序
nums1 = [4, 5, 6, 0, 0, 0]
m = 3
nums2 = [1, 2, 3]
n = 3
假如使用正序遍历nums1[0] > nums2[0],这个时候需要把nums2[0]数据放到nums1[0]位置,但是nums1[0]当前还保存了有效数据。如果直接交换数据就会变成如下所示
nums1 = [1, 5, 6, 0, 0, 0]
m = 3
nums2 = [4, 2, 3]
n = 3
这个时候会造成nums2变成一个无序数组,后续处理就变的特别麻烦。
如果采用倒序就完全没有这个问题,不会存在保存nums2数据时与nums1原始有效数据冲突问题。
停止条件
这个就比较简单,因为是倒序遍历,所以只两个数组的索引大于等于0就一直循环遍历下去。
判断条件
1.如果nums1和nums2都有数据将比较小的数据放入nums1中记录索引位置,并把效小元素的数组索引-1.
2.如果只有nums1有剩余数据,表示出现如下情况可以直接停止循环。
3.只有nums2有剩余数据,就需要将数据拷贝到nums1上。
3. 演示
class Solution(object):
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_index = m - 1
nums2_index = n - 1
real_index = m + n - 1
while nums1_index >= 0 or nums2_index >= 0:
if nums1_index >= 0 and nums2_index >= 0:
if nums1[nums1_index] > nums2[nums2_index]:
nums1[real_index] = nums1[nums1_index]
nums1_index -= 1
else:
nums1[real_index] = nums2[nums2_index]
nums2_index -= 1
elif nums1_index >= 0:
break
else:
nums1[real_index] = nums2[nums2_index]
nums2_index -= 1
real_index -= 1
if __name__ == '__main__':
nums1 = [1, 2, 3, 0, 0, 0]
m = 3
nums2 = [2, 5, 6]
n = 3
s = Solution()
s.merge(nums1, m, nums2, n)
print(nums1)