5-line C++ solution, one loop


  • 0
    W
        void moveZeroes(vector<int>& nums) {
            int distance = 0;
            for(int i=0; i<nums.size(); i++){
                if(nums[i]!=0 && i-distance!=i) swap(nums[i-distance], nums[i]);
                else if(nums[i]==0)    distance++;
            }
        }
    

Log in to reply
 

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