Elegant Solution using a tail pointer (16ms)


  • 0
    N
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int tail = 0;  //points to 1 past the last non-zero entry
            for (int i=0; i<nums.size(); i++) {
                if (nums[i] == 0)
                    continue;
                
                if ((tail++) != i) {
                    nums[tail-1] = nums [i]; //Overwrite since there are 0s in the middle
                    nums[i] = 0;
                }
            }
        }
    };

Log in to reply
 

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