# 1089. Duplicate Zeros

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:

``````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:

``````Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]
``````

Note:

1. `1 <= arr.length <= 10000`
2. `0 <= arr[i] <= 9`

``````class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int n = arr.size();
vector<int> res;
for (int i = 0; i < n && res.size() < n; ++i) {
res.push_back(arr[i]);
if (arr[i] == 0 && res.size() < n) res.push_back(0);
}
arr = res;
}
};
``````

``````class Solution {
public:
void duplicateZeros(vector<int>& arr) {
vector<int> vec = arr;
int i = 0, j = 0, n = arr.size();
while (i < n) {
arr[i] = vec[j];
if (arr[i] == 0 && i + 1 < n) arr[++i] = 0;
++i; ++j;
}
}
};
``````

``````class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int n = arr.size(), j = n + count(arr.begin(), arr.end(), 0);
for (int i = n - 1; i >= 0; --i) {
if (--j < n) arr[j] = arr[i];
if (arr[i] == 0 && --j < n) arr[j] = 0;
}
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1089

https://leetcode.com/problems/duplicate-zeros/

https://leetcode.com/problems/duplicate-zeros/discuss/312743/JavaC%2B%2B-O(n)-or-O(1)

https://leetcode.com/problems/duplicate-zeros/discuss/312727/C%2B%2BJava-Two-Pointers-Space-O(1)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation