-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMoveZeroes.java
36 lines (33 loc) · 1.17 KB
/
MoveZeroes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class MoveZeroes {
public static void main(String[] args) {
int[] nums = new int[]{0, 1, 0, 3, 12};
new MoveZeroes().moveZeroes(nums);
for (int x : nums) {
System.out.print(x + " ");
}
}
public void moveZeroes(int[] nums) {
if (nums != null && nums.length > 0) {
int length = nums.length;
int[] zeroArray = new int[length + 1];
int[] nonZeroArray = new int[length + 1];
int zeroIndex = 0;
int nonZeroIndex = 0;
for (int i = 0, j = length -1; i < j; i++, j--) {
if (nums[i] == 0) {
zeroArray[zeroIndex++] = i + 1;
} else {
nonZeroArray[nonZeroIndex++] = i + 1;
}
}
for (int i = 0; i < zeroArray.length; i++) {
int zIndex = zeroArray[i];
int nzIndex = nonZeroArray[i];
if (zIndex > 0 && zIndex < nzIndex) {
nums[zIndex - 1] = nums[nzIndex - 1];
nums[nzIndex - 1] = 0;
}
}
}
}
}