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

本文介绍了一种将两个已排序的整数数组合并为一个有序数组的方法。利用了第一个数组足够大的特性,通过从后向前比较并填充元素的方式,实现两数组的合并。此方法适用于数组1有足够的预留空间来存放数组2的全部元素。
560

被折叠的 条评论
为什么被折叠?



