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.
Subscribe
to see which companies asked this question
主要是利用,数组1比较大的优势,可以从后往前比较,直接从nums1[m+n-1]开始填数
题目的输入也比较败家,nums1的输入,必须保证初始数组的长度就大于m+n才行。
class Solution(object):
def merge(self, nums1, m, nums2, n):
pm = m - 1
pn = n - 1
pos = m+n-1
while pos >= 0 and pm >= 0 and pn >= 0:
#print pos,pm,pn
if nums1[pm] > nums2[pn]:
nums1[pos] = nums1[pm]
pos -= 1
pm -= 1
else:
nums1[pos] = nums2[pn]
pos -= 1
pn -= 1
while pm >= 0:
nums1[pos] = nums1[pm]
pos -= 1
pm -= 1
while pn >= 0:
nums1[pos] = nums2[pn]
pos -= 1
pn -= 1