Monday, June 5, 2017

Move Zeros

Problem Statement

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


For example, given nums = [0, 1, 0, 3, 12], after calling your function, 
nums should be [1, 3, 12, 0, 0].



Link to GitHub :Code

Solution

  • We need a variable insertPos which would be used to replace elements with zero with the current element ex 0, 1 would be replaced by  1,0
  • The count of insertPos  lets us know how many zeros need to be replaces towards the end of the array
  • Keep replacing the end of the array with 0 it is less than array length
public static void get(int arr[])
 {
  if (arr==null || arr.length==0 ) return;
  //Loop through the array to find zeros
  int insertpos=0;
  for(int n: arr)
  {
   if(n!=0)
   arr[insertpos++]=n;
   
  }
  //This is where we replace end of the array 
                 //with zero based on the insertPos count
  while(insertpos < arr.length)
  {
   arr[insertpos++]=0;
  }
 }








No comments:

Post a Comment