-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMoveZeroes.java
68 lines (57 loc) · 1.44 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.leetcode.algorithms.easy.array;
import java.util.Arrays;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class MoveZeroes {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int[] nums = InputUtil.integerArr(inputs);
// Output
moveZeroes(nums);
scanner.close();
}
public static void moveZeroes(int[] nums) {
int length = nums.length;
int i = 0;
int index = 0;
int trailingZeroIndex = length - 1; // Initiate trailing zero index
boolean isAllZeroes = false;
while(i < length) {
// Check if not equals '0' then update index 'i'
if(nums[i] == 0) {
if(i >= trailingZeroIndex) {
++i;
} else {
// Update current trailing zero index
while((nums[trailingZeroIndex - index] == 0) && (trailingZeroIndex - index > 0)) {
if(trailingZeroIndex - index > 0) {
++index;
} else {
// The whole array are zeroes
isAllZeroes = true;
break;
}
}
if(isAllZeroes) {
break;
}
trailingZeroIndex -= index;
// Loop until '0' reaching trailing zero index
int j = i;
while(j < trailingZeroIndex) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
++j;
}
}
} else {
++i;
}
}
// Print output
System.out.println(Arrays.toString(nums));
}
}