File tree Expand file tree Collapse file tree 2 files changed +31
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -54,4 +54,26 @@ public void moveZeroes(int[] nums) {
54
54
}
55
55
}
56
56
57
+ public static class Solution4 {
58
+ /**
59
+ * I'm glad that I finally figured this one out completely on my own, this O(n) time, O(1) space solution.
60
+ */
61
+ public void moveZeroes (int [] nums ) {
62
+ int i = 0 ;//zero index
63
+ int j = 0 ;//non zero index
64
+ while (i < nums .length && j < nums .length ) {
65
+ if (nums [j ] != 0 ) {
66
+ if (i < j ) {
67
+ nums [i ] = nums [j ];
68
+ nums [j ] = 0 ;
69
+ }
70
+ }
71
+ j ++;
72
+ while (i < nums .length && nums [i ] != 0 ) {
73
+ i ++;
74
+ }
75
+ }
76
+ }
77
+ }
78
+
57
79
}
Original file line number Diff line number Diff line change @@ -11,13 +11,15 @@ public class _283Test {
11
11
private static _283 .Solution1 solution1 ;
12
12
private static _283 .Solution2 solution2 ;
13
13
private static _283 .Solution3 solution3 ;
14
+ private static _283 .Solution4 solution4 ;
14
15
private static int [] nums ;
15
16
16
17
@ BeforeClass
17
18
public static void setup () {
18
19
solution1 = new _283 .Solution1 ();
19
20
solution2 = new _283 .Solution2 ();
20
21
solution3 = new _283 .Solution3 ();
22
+ solution4 = new _283 .Solution4 ();
21
23
}
22
24
23
25
@ Test
@@ -124,4 +126,11 @@ public void test15() {
124
126
solution3 .moveZeroes (nums );
125
127
assertArrayEquals (new int []{1 , 1 , 0 }, nums );
126
128
}
129
+
130
+ @ Test
131
+ public void test16 () {
132
+ nums = new int []{2 , 1 };
133
+ solution4 .moveZeroes (nums );
134
+ assertArrayEquals (new int []{2 , 1 }, nums );
135
+ }
127
136
}
You can’t perform that action at this time.
0 commit comments