题目地址
https://leetcode-cn.com/problems/merge-sorted-array/
题目描述
给定两个有序整数数组 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]
代码初步
- 思路:
两个数组合并之后再排序
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[m:m+n]=nums2[:n]
nums1.sort()
代码欣赏
- 思路1:两个数组合并之后,再冒泡排序(不用内置排序函数)
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.
"""
# 归并
j=0
for i in range(m,m+n):
nums1[i]=nums2[j]
j=j+1
# 冒泡排序
for i in range(0,m+n-1):
for j in range(0,m+n-1-i):
if (nums1[j]>nums1[j+1]):
tmp = nums1[j+1]
nums1[j+1]=nums1[j]
nums1[j]=tmp
j=j+1
i=i+1
- 思路2:直接对nums1进行操作排序
为什么最后要加一个 while(n >= 0): 而不是 while(m >= 0):?
首先前面的判断语句 m >= 0 and n >= 0 只需要前面的 m<0便跳出循环, 而如果 m >=0 而 n<0 的情况下, 那么前面的数组已经有序, 不需要进行插入了.
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.
"""
#从后面开始排序
while(m>0 and n>0):
if(nums1[m-1]<nums2[n-1]):
nums1[n+m-1]=nums2[n-1]
n=n-1
else:
nums1[n+m-1]=nums1[m-1]
m=m-1
# m<0跳出上面的循环了,n还大于0,将nums2剩余的数搬到nums1的前面
while n>0:
nums1[n-1]=nums2[n-1]
n=n-1