Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).
Solution 1:
It rerains ordering.
// move all zeros to end of array, keep the non-zero elements order
public static void moveZeroToEnd(int[] A) {
int n = A.length, cnt = 0;
for(int i=0; i<n; i++) {
if(A[i] != 0) {
A[cnt++] = A[i];
}
}
while(cnt < n) {
A[cnt++] = 0;
}
}
Solution 2:
It does not keep the non-zero elements order.
// move all zeros to end of array, does not keep the non-zero elements order
public static void moveZeroRight(int[] A) {
for(int i=0, j=A.length-1; i<j; i++) {
if(A[i] == 0) {
while(j>i && A[j] == 0) j--;
swap(A, i, j);
}
}
}
private static void swap(int[] A, int i, int j) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}