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.
解题思路:
这题已经告诉nums1有足够的空间,因此可以利用这多余的空间做文章。
从nums1和nums2最大的元素开始比较,依次安排到nums1多余的空间中。如果nums2最后还存在比nums1中小的数字,则把nums2中剩余的数字依次放到nums1中。
Python实现:
class Solution:
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.
"""
i = m - 1; j = n - 1
k = m + n - 1
while i >= 0 and j >= 0: # 从大到小,把大的元素依次移到后面
if nums1[i] < nums2[j]:
nums1[k] = nums2[j]
j -= 1
else: # 否则,把nums1中的元素后移一位
nums1[k] = nums1[i]
i -= 1
k -= 1
while j >= 0: # 如果nums2中存在比nums1最小数字还要小的数字,则依次加入到nums1中
nums1[k] = nums2[j]
k -= 1
j -= 1
return
a = [1,2,4,5,6,-1] # 用 -1 表示占位,即多余的空间
m = 5
b = [3]
n = 1
c = Solution()
print(c.merge(a,m,b,n)) # [1,2,3,4,5,6]