class Solution {
public:
void duplicateZeros(vector<int>& arr) {
vector<int> temp(arr.size());
temp[0] = 0;
for (int i = 0; i < arr.size() - 1; i++)
{
if (arr[i] == 0) {
temp[i+1] = temp[i] + 1;
} else {
temp[i+1] = temp[i];
}
}
for (int j = arr.size() - 1; j >= 0; j--)
{
if (j + temp[j] <= arr.size() - 1) {
arr[j + temp[j]] = arr[j];
if (arr[j] == 0 && (j + temp[j] < arr.size() -1)) {
arr[j + temp[j] + 1] = 0;
}
}
}
}
};
思路
先遍历一边数组,开辟一个辅助数组,记录对应位置需要向后移动的位数;
从后向前再遍历数组,对应位置加上后移位数,如果在数组范围,则将对应元素后移,若该元素为零,需要复写,所以其后一位赋值为零;
要点
边界条件:在元素后移之后,又判断该后移元素为零,则应该将后一个元素赋值为零,若该元素正好移动到数组尾部,则会溢出,因而需要加一个限制条件解决边界问题