The practice of fast and slow pointer【2】

The study arrangement is based on "Code Caprice"~

leetcode 283 moving zero

Ideas:

[1] Sort directly from big to small? - No, keep the original relative order

[2] Fast and slow pointer - how to shift 0?

===> Fast and slow pointer + assignment

Code:

class Solution {
public:

    void moveZeroes(vector<int>& nums) 
    {
        int slow=0;
        for(int  fast=1;fast<=nums.size()-1;fast++)//必须有=号
        {
            if(nums[slow]==0)
            {
                if(nums[fast]==0)
                continue;
                else
                {
                    nums[slow++]=nums[fast];
                    nums[fast]=0;
                }
            }
            else 
            slow++;
            
        }

    }
};

 Discuss:

fast<nums.size()-1【X

As a result, after the fast pointer reaches the last element, the loop is directly jumped out, and the assignment operation is no longer performed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324162567&siteId=291194637