1.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.
2.题目要求:混合插入有序数组,由于两个数组都是有序的,所有只要按顺序比较大小即可。
3.方法:建立一个m+n大小的新数组,然后逐个从A和B数组中取出元素比较,把较小的加入新数组,然后在考虑A数组有剩余和B数组有剩余的两种情况,最后在把新数组的元素重新赋值到A数组中即可。
4.代码:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
multiset<int> result;
for(int i = 0;i<m;i++)
{
result.insert(nums1[i]);
}
for(int i = 0;i<n;i++)
{
result.insert(nums2[i]);
}
nums1.clear();
set<int>::iterator iter = result.begin();
for(;iter!=result.end();iter++)
{
nums1.push_back(*iter);
}
}
};