- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathMoveZerosToEnd.java
39 lines (29 loc) Β· 677 Bytes
/
MoveZerosToEnd.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
37
38
39
packagegfg.Arrays;
importjava.util.Arrays;
publicclassMoveZerosToEnd {
publicstaticvoidmain(String[] args) {
int[] arr = { 8, 5, 0, 10, 0, 20 };
System.out.println("original array: " + Arrays.toString(arr));
moveZerosToRight(arr);
System.out.println("\nafter moving zeros to end: " + Arrays.toString(arr));
}
// O(n) time
publicstaticvoidmoveZerosToRight(int[] arr) {
if (arr.length < 1) {
return;
}
intreader = 0;
intwriter = 0;
while (reader < arr.length) {
if (arr[reader] != 0) {
arr[writer] = arr[reader];
writer++;
}
reader++;
}
while (writer < arr.length) {
arr[writer] = 0;
writer++;
}
}
}