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 <= arr.length <= 10000
0 <= arr[i] <= 9
题目大意:
如果数组中遇到0我们将其多复制一次将之后数向后移动,长度不超过原始长度。
解题思路:
暴力即可,遇到零从后向前调整每一位。
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int cor_idx = 0;
while(cor_idx<arr.size()){
if(arr[cor_idx]==0 && cor_idx != arr.size()-1){
int tmp_idx = arr.size()-1;
while(tmp_idx >= cor_idx+2){
arr[tmp_idx] = arr[tmp_idx-1];
tmp_idx--;
}
arr[cor_idx+1] = 0;
cor_idx += 2;
}else{
cor_idx++;
}
}
}
};