面试题 10.01

You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.

Initially the number of elements in A and B are m and n respectively.

Example:

Input: A = [1,2,3,0,0,0], m = 3 B = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

Solutions

  1. merge backwards

class Solution {
public:
    void merge(vector<int>& A, int m, vector<int>& B, int n) {
        int w = A.size();
        while (n > 0) {
            if (m > 0 && A[m - 1] > B[n - 1])
                A[--w] = A[--m];
            else
                A[--w] = B[--n];
        }
    }
};

Last updated

Was this helpful?