1 条题解
-
0
【例51.2】 插入元素
解题思路
把新值插到原第x个元素之前,即vector的begin()+x-1位置,原x及以后的元素顺次后移。
正确性说明
按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。
易错点
插入后长度n+1;样例位置2表示新数成为第二项。
复杂度
时间O(n),空间O(n)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<long long> a(n); for (auto &x : a) cin >> x; int pos; long long value; cin >> pos >> value; a.insert(a.begin() + pos - 1, value); for (size_t i = 0; i < a.size(); i++) { if (i) cout << " "; cout << a[i]; } cout << "\n"; return 0; }
- 1