283. Move Zeroes (Leetcode)

PHOTO EMBED

Wed Oct 06 2021 07:37:13 GMT+0000 (UTC)

Saved by @Sakshamkashyap7 #c++

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for(int i = 0, j = 0; i < nums.size(); i++) {
            if(nums[i]) {
                swap(nums[i],nums[j++]);
            }
        }
    }
};


//2nd approach
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int zero = 0, one = 0, n = nums.size()-1;
        while(zero < n && one < n)  {
            while(zero < n && nums[zero] != 0)  {
                zero++;
            }
            one = zero;
            while(one < n && nums[one] == 0)    {
                one++;
            }
            swap(nums[zero],nums[one]);
            zero++; 

        }
    }
};
content_copyCOPY

Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]

https://leetcode.com/problems/move-zeroes/