Leetcode 1089 Copy Zero
Idea: double pointer
Step 1: use the pointer cur to record the last digit to be copied, and use the pointer dest to point to the position where the last digit is to be copied;
Implementation process: at the beginning, cur points to 0, and dest points to -1. When arr[cur] != 0, dest takes two steps, otherwise it takes one step; determine whether dest is already at the end of the array or has crossed the boundary;
Step 2: If the array is out of bounds, let arr[arr.size()-1] = 0; dest -= 2; cur --;
Step 3: Complete the copying from the back to the front according to the requirements.
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int cur = 0 , dest = -1;
//确定要复习的最后一位数,使用cur指针指向
while(cur < arr.size())
{
if(arr[cur] !=0)
{
dest++;
}else{
dest +=2;
}
//当dest指针指向数组最后一个位置或者越界一位,跳出循环,不再让cur 往后走
if(dest >= arr.size()-1)
{
break;
}
++cur;
}
// 如果dest处于arr.size()的位置
if(dest == arr.size())
{
arr[arr.size()-1] = 0;
dest -=2;
--cur;
}
// 从右往左依次完成复
while(cur >=0)
{
if(arr[cur])
{
arr[dest--] = arr[cur--];
}else{
arr[dest--] = 0;
arr[dest--] = 0;
cur--;
}
}
}
};