Leetcode- merge two ordered arrays-5

Combine two ordered arrays

The question asks
  you to give you two ordered integer arrays nums1 and nums2, and asks to merge the integers in nums2 into nums1, and make nums1 also an ordered array.
Ideas
  for space complexity minimum, we can not create a new array, we need directly into nums1, considering the time complexity should be as small as possible, we can combine two elements in the array is compared, small place In nums1, the subscript is small, but considering that this will overwrite the original value in nums1, we assume that the size in nums1 is just enough to fit all the elements in the two arrays, then we can discharge from back to front , Which means that the elements in the two arrays are compared, and the larger element is placed at the end of the nums1 array, and inverse filling is performed until the array is filled.
Code

void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
	int p = m + n - 1;
	int p1 = m - 1;
	int p2 = n - 1;

	while (p1 >= 0 && p2 >= 0)
	{
		if (nums1[p1] >= nums2[p2])
		{
			nums1[p] = nums1[p1];
			p1--;
		}
		else
		{
			nums1[p] = nums2[p2];
			p2--;
		}
		p--;
	}
	if (p1 == -1)
	{
		while (p2 >= 0)
		{
			nums1[p] = nums2[p2];
			p2--;
			p--;
		}
	}
}

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/113129564