LeetCode-面试题10.01. Sorted Merge LCCI(合并排序的数组)

合并排序的数组

LeetCode-面试题10.01. Sorted Merge LCCI(合并排序的数组)_第1张图片

Sorted Merge LCCI

LeetCode-面试题10.01. Sorted Merge LCCI(合并排序的数组)_第2张图片

方法一:直接排序
AB合并后再排序

class Solution {
public:
    void merge(vector<int>& A, int m, vector<int>& B, int n) {
        for (int i = 0; i < n; i++) {
            A[m + i] = B[i];
        }
        sort(A.begin(), A.end());

    }
};

方法二:双指针
需要一个O(m+n)的辅助空间

class Solution {
public:
    void merge(vector<int>& A, int m, vector<int>& B, int n) {
        int pa = 0, pb = 0;
        vector<int>sorted;
        while (pa < m && pb < n) {
            if (A[pa] <= B[pb]) {
                sorted.push_back(A[pa++]);
            } else {
                sorted.push_back(B[pb++]);
            }
        }
        if (pa == m) {
            while (pb < n) {
                sorted.push_back(B[pb++]);
            }
        }
        if (pb == n) {
            while (pa < m) {
                sorted.push_back(A[pa++]);
            }
        }
        for (int i = 0; i < m + n; i++) {
            A[i] = sorted[i];
        }

    }
};

方法三:逆向双指针
可以原地修改

class Solution {
public:
    void merge(vector<int>& A, int m, vector<int>& B, int n) {
        int pa = m - 1, pb = n - 1;
        int cur = m + n - 1;
        while (pa >= 0 && pb >= 0) {
            if (A[pa] <= B[pb]) {
                A[cur--] = B[pb--];
            } else {
                A[cur--] = A[pa--];
            }
        }
        if (pb >= 0) {
            for (int i = 0; i <= pb; i++) {
                A[i] = B[i];
            }
        }
    }
};

你可能感兴趣的:(LeetCode)