Lintcode 合并排序数组 II

合并两个排序的整数数组A和B变成一个新的数组。

 注意事项

你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。

样例

给出 A = [1, 2, 3, empty, empty], B = [4, 5]

合并之后 A 将变成 [1,2,3,4,5]

标签 
排序数组  数组  脸书
分析:本题考虑移动最少的元素,则需要从后往前进行插入,总的元素数已经给出了则从A[m+n-1]向前进行插入。

class Solution {
public:
    /**
     * @param A: sorted integer array A which has m elements, 
     *           but size of A is m+n
     * @param B: sorted integer array B which has n elements
     * @return: void
     */
    void mergeSortedArray(int A[], int m, int B[], int n) {
        // write your code here
        while(n){
            if(m==0){
                for(int i=0;i=A[m-1]){
            A[m+n-1]=B[n-1];
            n--;
            }
            else{
            A[n+m-1]=A[m-1];
            m--;
            }
        }
    }
};


如有问题请留言。

转载请先联系博主,谢谢。


你可能感兴趣的:(LintCode编程)