Merge Sorted Array
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 tom+n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
two pointers
A和B都已经是排好序的数组,只能利用A后面的空间来插入,所以只需要从后往前比较就可以了。
因为A有足够的空间容纳A + B,我们使用游标i指向m + n - 1,也就是最大数值存放的地方,从后往前遍历A,B,谁大就放到i这里,同时递减i。
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: void Do not return anything, modify nums1 in-place instead.
"""
"""
for i in xrange(len(nums2)):
#nums1.append(nums2[i]) #要注意nums1的长度,如果nums1长度为0,即使里面有item,例如[1]m=0,则返回错误答案。
nums1[i+m] = nums2[i]
return nums1.sort()
"""
end = m+n-1
l1=m-1
l2 = n-1
while end >= 0:
if l1>=0 and l2>=0: #if nums1 and nums2 are left
if nums1[l1] > nums2[l2]:
nums1[end] = nums1[l1]
l1 -= 1
else:
nums1[end] = nums2[l2]
l2 -= 1
elif l1>=0 and l2 < 0: #if nums1 left
nums1[end] = nums1[l1]
l1 -= 1
elif l2>=0 and l1<0: #if nums2 left
nums1[end] = nums2[l2]
l2 -=1
end -= 1
简化
def merge(self, nums1, m, nums2, n):
l1, l2, end = m-1, n-1, m+n-1
while l1 >= 0 and l2 >= 0:
if nums2[l2] > nums1[l1]:
nums1[end] = nums2[l2]
l2 -= 1
else:
nums1[end] = nums1[l1]
l1 -= 1
end -= 1
if l1 < 0: # if nums2 left
nums1[:l2+1] = nums2[:l2+1]
如果单独nums1 left或者单独nums2 left,那么跳出循环,
nums1 left,只需要在原位就好
nums2 left, 需要把nums2留下的所有值放入nums1的前半部分
Last updated
Was this helpful?