Clean C++ one pass AC with explanation


  • 5
    A
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            
            int pos = 0; //last non zero element in nums after one pass
            
            for(int i = 0; i < nums.size(); i++)
            {
                if(nums[i] != 0)
                    swap(nums[pos++], nums[i]);
            }
        }
    };
    

    Simply, using two integers i and pos, for-loops represent the one pass, integer pos indicate the recent position of none zero element in vector nums after SWAP. Enjoy.


Log in to reply
 

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