1028-数组合并

原题
**题目描述**给出两个有序的整数数组 和 ,请将数组 合并到数组 中,变成一个有序的数组注意:可以假设 数组有足够的空间存放 数组的元素, 和 中初始的元素数目分别为 和

思想:
本题考察的是双指针的应用;

可以新建一个新的数组,用来存放两者的结果;

首先比较AB中数字的大小,如果A中的数字小于B中的数字,则将A中的数字放到新建的数组C的后面,此处C命名为temp,否则是B中的放到后面;

当A或B中的某一个指针移动到末尾时,说明A或B的数字已经全部加到了temp的后面,但有另外一个数组的数据还没有添加完,因此,再写两个while循环,将剩余的数据放到新建的数组的后面;

最后,将temp中的数字,全部赋值到A中;

不能对temp数组直接赋值,需要用memset()初始化…

class Solution {
    
    
public:
    void merge(int A[], int m, int B[], int n) {
    
    
        int len = m + n;
        int temp[len];
        memset(temp,0, sizeof(int)*(len));
        int i=0, j=0, k=0;
        while(i<m && j< n)
        {
    
    
            if(A[i] <= B[j])
            {
    
    
                temp[k++] = A[i++];
            }else 
                temp[k++] = B[j++];
        }
        while(i < m)
        {
    
    
            temp[k++] = A[i++];
        }
        while(j < n)
        {
    
    
            temp[k++] = B[j++];
        }
        
        for(int i=0; i<len; i++)
        {
    
    
            A[i] = temp[i];
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45885232/article/details/109346619
今日推荐