The description of the problem
Given a fixed-length integer array arr, 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 and do not return anything.
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/duplicate-zeros
an example
Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/duplicate-zeros
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The codes
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int n = arr.size();
stack<int> sta;
for (auto a : arr) {
if (a) {
sta.push(a);
} else {
for (int i = 0; i < 2; ++i) {
if (sta.size() == n) break;
sta.push(0);
}
}
if (sta.size() == n) break;
}
for (int i = n -1; i >= 0; --i) {
arr[i] = sta.top();
sta.pop();
}
}
};
int main()
{
Solution s;
vector<int> arr = {1,0,2,3,0,4,5,0};
cout << "The original array is: ";
for (auto a : arr) {
cout << a << " ";
}
s.duplicateZeros(arr);
cout << "\nThe new array is: ";
for (auto a : arr) {
cout << a << " ";
}
}
The results
$ ./test
The original array is: 1 0 2 3 0 4 5 0
The new array is: 1 0 0 2 3 0 0 4 %