[Sword pointing to offer|3. Merge two ordered arrays]

0. Merge two sorted arrays

image-20230408133816123

Question: There are two arrays A1 and A2 arranged in ascending order. There is enough free space at the end of A1 to accommodate A2. Please implement a function to insert all the numbers in A2 into A1, and all the numbers are is sorted.

  • nums1.length == m + n
  • nums2.length == n

Solution: This question is similar to [Sword Finger Offer | 2. Replace Spaces]. When merging arrays (strings), if you move each number from front to back, you need to move the number multiple times, so we can consider moving from back to front. Mobile, thereby increasing efficiency.

1.C language version

void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
    //目标就是把nums2中的元素挪完-->end2==>0
    //下面的deadLine,end1,end2都是对应的下标--双指针
    int deadLine=m+n-1;
    int end1=m-1;
    int end2=n-1;
    while(end1>=0&&end2>=0)
    {
        if(nums1[end1]>nums2[end2])
        {
            nums1[deadLine--]=nums1[end1--];
        }
        else
        {
            nums1[deadLine--]=nums2[end2--];
        }
    }
    //到这里如果end2==0的话,就说明num2挪完了,任务完成了;如果是end1==0的话,直接把nums2中剩余元素挪动到num1中即可
    if(end1<0)
    {
        while(end2>=0)
        {
            nums1[deadLine--]=nums2[end2--];
        }
    }
}

Let’s complain: this parameter num1Size is a bit redundant!

2.C++ version

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int deadLine=nums1.size()-1;
        int end1=m-1;
        int end2=n-1;
        while(end1>=0&&end2>=0)
        {
            if(nums1[end1]>nums2[end2])
            {
                nums1[deadLine--]=nums1[end1--];
            }
            else
            {
                nums1[deadLine--]=nums2[end2--];
            }
        }
        if(end1<0)
        {
            while(end2>=0)
            {
                nums1[deadLine--]=nums2[end2--];
            }
        }
    }
};

Guess you like

Origin blog.csdn.net/qq_64428099/article/details/130029111