C++ Solution with one iteration


  • 0
    Y
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            if(nums.size() == 0)
                return ;
            int cnt_zero = 0, fast = 0, slow = 0;
            int n = nums.size();
            for(; fast < n; ++ fast){
                if(nums[fast]){
                    nums[slow ++] = nums[fast];
                }else{
                    ++ cnt_zero;
                }
            }
            while(cnt_zero){
                nums[slow ++] = 0;
                -- cnt_zero;
            }
            return ;
        }
    };

Log in to reply
 

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