You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
answer:
I was able to write the code in O(n) space complexity.
Can we write this code in O(1) space complexity ?
What I have tried:
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
int i,j=0,k=0;
int a[m+1];
a[m]=0;
for(i=0;i<m;i++)
{
a[i]=nums1[i];
}
i=0;
while(i<m && j<n )
{
if(a[i]<nums2[j])
{
nums1[k++]=a[i++];
}
else
{
nums1[k++]=nums2[j++];
}
}
if(i!=m || j!=n)
{
for(;i<m;i++)
{
nums1[k++]=a[i];
}
for(;j<n;j++)
{
nums1[k++]=nums2[j];
}
}
}