C++ short solution.


  • 0
    C

    The same idea as: Remove Element

    void moveZeroes1(vector<int>& nums) {
        int tail = 0;
        for (int& num: nums)
            if (num != 0)
                nums[tail++] = num;
        for (int i=tail; i<nums.size(); i++)
            nums[i] = 0;
    }
    
    // exchange zero and non-zero elements 
    void moveZeroes(vector<int>& nums) {
        int tail = 0;
        for (int i=0; i<nums.size(); i++)
            if (nums[i]!=0) {
                int tmp = nums[i];
                nums[i] = nums[tail];
                nums[tail++] = tmp;
            }
    }
    

Log in to reply
 

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