Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
The number of elements initialized in nums1 and nums2 are m and n respectively.
题意:将已排序的两数组,一个拼接到另一个
方法一:将数组2直接拼接到数组1的后面,sort排序即可
Runtime: 49 ms
class Solution(object):
def merge(self, nums1, m, nums2, n):
for i in range(n):
nums1[i+m]=nums2[i]
nums1.sort()
方法二:类似于21. Merge Two Sorted Lists ,使用一个临时数组,依次比较两数组加入临时数组
注意:m,n是指第一组数和第二组数中有效需要排序的数,所以len(nums1)不一定等于m
由于结果要保存在第一个数组里,所以还要保证数组一要有m+n个空间。
Runtime: 59 ms
class Solution(object):
def merge(self, nums1, m, nums2, n):
tem=[]
i=j=0
while i!=m and j!=n:
if nums1[i]<nums2[j]:
tem.append(nums1[i])
i=i+1
else:
tem.append(nums2[j])
j=j+1
while i!=m:
tem.append(nums1[i])
i=i+1
while j!=n:
tem.append(nums2[j])
j=j+1
for i in range(m+n):
nums1[i]=tem[i]