首页 > 代码库 > LeetCode Merge Sorted Array

LeetCode Merge Sorted Array

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int mi = m + n - 1;
        int ai = m - 1;
        int bi = n - 1;
        while (ai >= 0 && bi >= 0) {
            if (A[ai] >= B[bi]) {
                A[mi--] = A[ai--];
            } else {
                A[mi--] = B[bi--];
            }
        }
        while (ai >= 0) {
            A[mi--] = A[ai--];
        }
        while (bi >= 0) {
            A[mi--] = B[bi--];
        }
    }   
};

水一发,从末尾还是合并,可以安全的进行写入数组A