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.
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int* aux=new int[m+n];
for(int i=0;i<m;i++){
aux[i]=nums1[i];
}
for(int i=m;i<m+n;i++){
aux[i]=nums2[i-m];
}
for(int i=0;i<m+n;i++){
cout<<aux[i]<<" ";
}
cout<<endl;
//merge
int i=0,j=m;
for(int k=0;k<m+n;k++){
if(i>m-1){
nums1[k]=aux[j];j++;
} else if(j>m+n-1){
nums1[k]=aux[i];i++;
}
else if(aux[i]<aux[j]){
nums1[k]=aux[i];i++;
} else{
nums1[k]=aux[j];j++;
}
}
delete[] aux;
}
};
int main(){
int arr1[20]={1,2,3,5};
int arr2[]={5,6,8,9,10};
vector<int> val1(arr1,arr1+20);
vector<int> val2(arr2,arr2+sizeof(arr2)/sizeof(int));
int m=4,n=5;
Solution().merge(val1,m,val2,n);
for(int i=0;i<m+n;i++){
cout<<val1[i]<<" ";
}
cout<<endl;
}