Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your function.
Example 1:
1 2 3
Input: [1,0,2,3,0,4,5,0] Output: null Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
Example 2:
1 2 3
Input: [1,2,3] Output: null Explanation: After calling your function, the input array is modified to: [1,2,3]
Note:
1 <= arr.length <= 10000
0 <= arr[i] <= 9
解法1:库函数
使用resize()和insert()实现按照位置插入和数组长度不变。
1 2 3 4 5 6 7 8 9 10 11 12 13
class Solution { public: void duplicateZeros(vector<int>& arr) { int n = arr.size(); for (int i = 0; i < n; ++i) { if (arr[i] == 0) { arr.insert(arr.begin() + i, 0); ++i; } } arr.resize(n); } };