思路:设定两个指针ptrA和ptrB,遍历两个数组比较,对A数组进行修改;
A.insert添加,最后进行A.erase删除多余元素,提醒,数组长度提前记录一下,方便后续删除
#include <iostream>
#include <vector>using namespace std;class Solution {
public:void merge(vector<int>& A, int m, vector<int>& B, int n) {int ptr_A = 0;int ptr_B = 0;int length = m + n;for (; ptr_B < n && ptr_A < m; ptr_A++){if (A[ptr_A] > B[ptr_B]){A.insert(A.begin() + ptr_A, B[ptr_B]);m++;ptr_B++;}elsecontinue;}if (ptr_B < n)A.insert(A.begin()+m, B.begin() + ptr_B, B.end());A.erase(A.begin() + length, A.end());}
};int main(){Solution s;vector<int> A = {1,2,3,0,0,0};vector<int> B = {2,5,6};s.merge(A, 3, B, 3);for (auto i : A)cout << i << " ";return 0;
}