[Algorithm - Double Pointer] LeetCode 1089 Copy Zero

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.

  1. First find the last number that needs to be copied
    1. First determine the value of the cur position
    2. Determines whether dest moves back one step or two steps
    3. Determine whether dest has reached the end position
    4. cur++
  2. Handle edge cases (cases where dest exceeds arr.size()-1) 
  3. 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;
            }
        }
    }
};

result:

Guess you like

Origin blog.csdn.net/weixin_44906102/article/details/132265908