LeetCode — 283. Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Approach 1:  Using extra space

class Solution {
    public void moveZeroes(int[] nums) {

        int newarr[] = new int[nums.length];
        int count = 0;
        int ncp = 0;
        for(int num:nums)
        {
            if(num==0)
            {
                zeCo++;
            }
         
            else
                newarr[ncp++]=num;
        }
        while(zeCo-->0)
        {
                            newarr[ncp++]=0;

        }
        ncp=0;
        for(int num:newarr)
        {
            nums[ncp++] = num;
        }
     
    }

}

Approach 2: Without using extra space:

class Solution {
    public void moveZeroes(int[] nums) {

        int count = 0;
        int zc =0;
        for(int i=0; i< nums.length; i++)
        {
            if(nums[i]!=0)
            {nums[count] = nums[i];
            count++;
            }
     
            else
                zc++;
        }
        while(count<nums.length)
        {
                            nums[count++]=0;

        }
     
    }
}

Comments

Popular posts from this blog

Leetcode 1417. Reformat The String