Don't be fooled by the "simple" label on this question. In fact, there are many details that need to be paid attention to.
Topic description:
Problem-solving ideas:
Forward traversal, determine the position of the last element of the result array; fill in reverse order after knowing the position of the last element.
- First find the last number that needs to be copied
- First determine the value of the cur position
- Determines whether dest moves back one step or two steps
- Determine whether dest has reached the end position
- cur++
- Handle edge cases (cases where dest exceeds arr.size()-1)
- Complete the copy operation from back to front
Code:
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int cur = 0;
int dest = -1;
while(cur < arr.size())
{
if(arr[cur] == 0)
{
dest += 2;
}
else
{
dest++;
}
if(dest >= arr.size() - 1)
{
break;
}
cur++;
}
if(dest > arr.size() - 1)
{
arr[arr.size() - 1] = 0;
cur--;
dest -= 2;
}
while(cur >= 0)
{
if(arr[cur] != 0)
{
arr[dest] = arr[cur];
dest--;
cur--;
}
else
{
arr[dest] = 0;
arr[dest - 1] = 0;
cur--;
dest -= 2;
}
}
}
};