题目:
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 nums1and nums2 are m and n respectively.
题目解答:可以确定,两个有序数组在合并之后的大小为m + n,并且依旧有序。为了防止从前面访问元素时,导致元素移动次数过于频繁,可以直接从数组的最后面开始比较。思路很简单,就不赘述了,直接看代码吧。
代码如下:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int cur_Loc = m + n - 1;
int i = m - 1;
int j = n - 1;
nums1.resize(cur_Loc + 1);
while((cur_Loc >= 0) && (i >= 0) && (j >= 0) )
{
if(nums1[i] > nums2[j])
{
nums1[cur_Loc] = nums1[i];
i--;
}
else
{
nums1[cur_Loc] = nums2[j];
j--;
}
cur_Loc--;
}
if(i < 0)
{
while((cur_Loc >= 0) && (j >= 0) )
{
nums1[cur_Loc] = nums2[j];
j--;
cur_Loc--;
}
}
}
};