题目:
Given two sorted integer arrays
nums1
andnums2
, mergenums2
into nums1 as one sorted array.
Note:
The number of elements initialized innums1
andnums2
arem
andn
respectively. You may assume that nums1 has enough space (size that is greater or equal tom + n
) to hold additional elements from nums2.
Example:Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
解释:
给定两个排序后的数组nums1
和nums2
,把nums2
合并到nums1
中,使之变成一个排好序的数组。
核心思想是从后面开始更新nums1
。
python代码:
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.
"""
i=m-1
j=n-1
k=m+n-1
while i>=0 and j>=0:
if nums1[i]>nums2[j]:
nums1[k]=nums1[i]
i-=1
else:
nums1[k]=nums2[j]
j-=1
k-=1
while i>=0:
nums1[k]=nums1[i]
i-=1
k-=1
while j>=0:
nums1[k]=nums2[j]
j-=1
k-=1
优化一下代码:
python代码:
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.
"""
while m>0 and n>0:
if nums1[m-1]>=nums2[n-1]:
nums1[m+n-1]=nums1[m-1]
m-=1
else:
nums1[m+n-1]=nums2[n-1]
n-=1
#此时,nums1本身所有的元素都已经移动到了后面,只剩下num2的元素,需要移动到nums1的最前面
#此时,n等于几表示nums2中还剩下几个元素,如果n=0了,表示已经插入完成,不需要再进行插入操作了
if n>0:
nums1[:n]=nums2[:n]
c++代码:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
while (m>0 && n>0)
{
if (nums1[m-1]>=nums2[n-1])
{
nums1[m+n-1]=nums1[m-1];
m--;
}
else
{
nums1[m+n-1]=nums2[n-1];
n--;
}
}
while (n>0)
{
nums1[n-1]=nums2[n-1];
n--;
}
}
};
总结:
有时候如果可以直接使用题目中所给的变量作为指针的话,不需要额外定义新的指针了,比如说,本题目可以将题目所给的n
和m
作为指针,所以不需要自己再定义i
和j
了,这样能节省代码量,同时也可以用m+n-1
代替k
。