Ex:-
[ 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 ] ======> [ 1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0 ]
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class ArrayZero{ public static void main(String []args){ int[] arr = { 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 }; int[] result = moveZeroesToEnd(arr); for(int x: result) System.out.print(x+" "); } public static int[] moveZeroesToEnd(int[] arr){ int count = 0; for(int i=0; i<arr.length; i++) if(arr[i]!=0) arr[count++] = arr[i]; while(count<arr.length) arr[count++] = 0; return arr; } } |
Python
arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9] result = [None]*len(arr) count = 0 for i in range(len(arr)): if arr[i]!=0: arr[count] = arr[i] count += 1 while count<len(arr): arr[count]=0 count += 1 print(arr)