Skip to content

Commit 19492cb

Browse files
add a solution for 283
1 parent e3c7c87 commit 19492cb

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/main/java/com/fishercoder/solutions/_283.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,26 @@ public void moveZeroes(int[] nums) {
5454
}
5555
}
5656

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+
5779
}

src/test/java/com/fishercoder/_283Test.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ public class _283Test {
1111
private static _283.Solution1 solution1;
1212
private static _283.Solution2 solution2;
1313
private static _283.Solution3 solution3;
14+
private static _283.Solution4 solution4;
1415
private static int[] nums;
1516

1617
@BeforeClass
1718
public static void setup() {
1819
solution1 = new _283.Solution1();
1920
solution2 = new _283.Solution2();
2021
solution3 = new _283.Solution3();
22+
solution4 = new _283.Solution4();
2123
}
2224

2325
@Test
@@ -124,4 +126,11 @@ public void test15() {
124126
solution3.moveZeroes(nums);
125127
assertArrayEquals(new int[]{1, 1, 0}, nums);
126128
}
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+
}
127136
}

0 commit comments

Comments
 (0)