C++ two pointers solution with explanations


  • 0
    G
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) 
        {
            int Z = 0;
        
            //
            // Skip over nonzeros;
            //
            for(;Z != nums.size() && nums[Z] != 0; Z++);
            
            //
            // Start from the first 0 upto the end
            //
            
            for(int NZ = Z;NZ < nums.size();)
            {
                
                //
                // skip over zeros
                //
                
                if(nums[NZ] == 0)
                {
                    NZ++;
                }
                else
                {
                    swap(nums[Z],nums[NZ]);
                    
                    //
                    // update the zero index
                    //
                    
                    Z++;
                }
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.