Problem Statement
Given an arraynums
, 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].
Solution
Using python (Link to Github)
1 2 3 4 5 6 7 8 9 10 | ar =[0,0,4,7,0,10] def move_zeros(nums): last0=0; #move the non zero numbers to the left for i in range(0,len(nums)): if(nums[i]!=0): nums[i],nums[last0]=nums[last0],nums[i] last0+=1 return nums move_zeros(ar) |
Using Java (Code)
- 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