Leetcode.88 Merge two sorted arrays

Merge two sorted arrays

Article directory

Merge

Core idea: Compare in turn, take the smaller value and put it into the new array.
i traverse nums1, j traverse nums2, take the smaller value and put it into nums3.
If nums[i] and nums[j] are equal, put one in nums3

insert image description here

insert image description here

Then if nums[i] and nums[j] are equal, just put one in nums3

insert image description here

insert image description here

insert image description here

At this time, the elements in nums1 have been gone, then directly take the remaining elements in nums2 to nums3,
because nums2 is an ordered array, so there is no need to consider that the remaining elements of nums2 are smaller than nums3
insert image description here

insert image description here

The biggest problem with this general method is that a new array is created. If the title requires a space complexity of O(1), this method will not work.

Idea two

The merge is sequentially compared to take the smaller value, but the second idea is to compare the larger value sequentially. The
second idea is roughly similar to the merge.

Idea 2 overall idea:
i points to the last one of nums1effective element,Forward traversal,
j points to the last effective element of nums2, forward traversal
dst points to the last element of nums1, and also traverses forward
if the element pointed to by j is greater than the element pointed to by i, then put the element pointed to by j into dst in the location

insert image description here

insert image description here
insert image description here

insert image description here
insert image description here

When j traverses nums2 forward, we just let it end

But one more situation needs to be considered

insert image description here

When each element in nums1 is larger than each element in nums2, nums1 must be traversed first. At this time, each element of nums2 needs to be put into nums1 in advance
insert image description here

void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n)
{
    
    
  int i = m -1 ;
  int j = n- 1 ;
  int dst = m + n -1 ;
  while( i >=0 && j >= 0)
  {
    
    
      //nums2先走完 , j < 0 
      if( nums1[i]>= nums2[j])  //取较大值
      {
    
    
          nums1[dst] = nums1[i];
          dst-- ;
          i--;
      }
      else
      {
    
    
          nums1[dst]=nums2[j];
          dst--;
          j--;
      }
  }
    // nums1 先走完 , i < 0 
    while( j>=0 )
    {
    
    
        nums1[dst] = nums2[j];
      j -- ;
      dst -- ;
    }
}

If you think this article is helpful to you, you might as well move your fingers to like, collect and forward, and give Xi Ling a big attention. Every
support from you will be transformed into my motivation to move forward! ! !

Guess you like

Origin blog.csdn.net/qq_73478334/article/details/129517169