O(n) solution for move zero to right.


  • 5
    D
        public void MoveZero(int nums[])
    {
        int z=-1;
        for(int i=0;i<nums.Length;i++)
        {
            
            if(z!=-1 && nums[i]!=0)
            {
                int temp=nums[z];
                nums[z]=nums[i];
                nums[i]=temp;
                z++;
            }
            else if(nums[i]==0 && z==-1)
            {
                z=i;
            }
            
        }
    

    }


  • 0
    S

    good job!You chage this problem to make the zeros together at the end.


  • 0
    P

    but if there are other conditions: nums[i]! = 0 && z == -1,what should your program do?


  • 0
    R

    if z == -1 then the array do not contains zero, we not need to do anything.


Log in to reply
 

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