Simple easy to understand solution with O(1) memory


  • 0
    P
    class Solution {
    public:
        void moveZeroes(vector<int>& nums)
        {
            int len=nums.size();
            int idx=0;
            for(int i=0;i<len;i++)
            {
                if(nums[i]==0)
                {
                    continue;
                }
                nums[idx]=nums[i];
                idx++;
            }
            for(int i=idx;i<len;i++)
            {
                nums[i]=0;
            }
        }
    };

  • 0
    L
    void moveZeroes(vector<int>& nums) {
        int n=nums.size();
        int i,c[10001],j;
        for(i=0,j=0;i<n;++i)
        {
    	    if(nums[i]==0);
    	    else
    	    {
    		    c[j]=nums[i];
    		    j++;
    	    }
        }
        for(i=j;i<n;i++)
    	    c[i]=0;
        /*for(i=0;i<7;i++)
        {
    	   nums[i]=c[i];
        }*/
        nums.erase (nums.begin(),nums.end());
        nums.insert(nums.end(), &c[0], &c[n]);
    }

  • 0
    P

    Its using extra space


  • 0
    L

    I have used that method to do that question in simple way. We can also do it in the same array by swapping 0 with its next element.


Log in to reply
 

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