Share my C++ solution


  • 0
    R
    void moveZeroes(vector<int>& nums) 
    {
        int i = 0, j = 0, n = nums.size(), cnt = 0;
        while (i < n)
        {
            if (nums[i] != 0)
            {
                nums[j++] = nums[i];
            }
            else 
                ++cnt;
            ++i;
        }
        
        fill(nums.begin() + n - cnt, nums.end(), 0);
    }

  • -1
    U

    C++ solution using vector methods

    class Solution {
    public:
    
    void moveZeroes(vector<int>& nums) {
    
        int z=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]==0)
            {
                nums.erase(nums.begin()+i);
                i--;
                z++;
            }
        }
        for(int i=0;i<z;i++)
        {
            nums.push_back(0);
        }
    
        
    }};

Log in to reply
 

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