Given sorted integer Arrays nums1 and nums2, merge nums2 into nums1 as one sorted Array.
Note:
Assume that nums1 have enough space (size that's greater or equal to m + n) to hold add Itional elements from nums2. The number of elements initialized in nums1 and nums2 is m and n respectively.
There are two arrays, and the previous part of array 1 is useful data, followed by 0, to merge the array 2 array into the array 1.
Because the previous section of array 1 holds useful data, you need to traverse the array in the opposite direction
public class Solution {
public void merge ( int [] nums1 , int m int [] NUMS2 int n ) {
int index = nums1.Length - 1;
int index1 = m - 1;
int index2 = n - 1;
while (index1 >= 0 && index2 >= 0)
{
if (nums1[index1] > nums2[index2])
{
nums1[index] = nums1[index1];
index--;
index1--;
}
else
{
nums1[index] = nums2[index2];
index--;
index2--;
}
}
while (index1 >= 0)
{
nums1[index--] = nums1[index1--];
}
while (index2 >= 0)
{
nums1[index--] = nums2[index2--];
}
}
}
Null
88. Merge two sorted arrays Merge Sorted array