【链表与数组】Lintcode 64. 合并排序数组

Lintcode 64. 合并排序数组

题目描述:合并两个排序的整数数组A和B变成一个新的数组。
注:你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
在这里插入图片描述
这道题是 Lintcode 6. 合并排序数组 II 的简单变形,只是合并后的结果放在其中一个数组中,题目也比较简单。

这里只有一条需要注意的点:要从大到小进行操作,因为在数组中如果你从小到大合并到其中一个数组中的话,比如你将最小的数先放到A数组下标为0的位置,那下标1之后的所有元素都得向后移动一位,这会使得程序的执行效率很低。

class Solution {
    
    
public:
    /*
     * @param A: sorted integer array A which has m elements, but size of A is m+n
     * @param m: An integer
     * @param B: sorted integer array B which has n elements
     * @param n: An integer
     * @return: nothing
     */
    void mergeSortedArray(int A[], int m, int B[], int n) {
    
    
        //从大到小合并,避免大量数组内元素移动增加复杂度
        int idxA = m - 1, idxB = n - 1, idx = m + n - 1;
        while (idxA >= 0 && idxB >= 0) {
    
    
            if (A[idxA] > B[idxB]) {
    
    
                A[idx--] = A[idxA--];
            } else {
    
    
                A[idx--] = B[idxB--];
            }
        }
        
        while (idxA >= 0) {
    
    
            A[idx--] = A[idxA--];
        }
        while (idxB >= 0) {
    
    
            A[idx--] = B[idxB--];
        }
    }
};

猜你喜欢

转载自blog.csdn.net/phdongou/article/details/113828437