Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit19492cb

Browse files
add a solution for 283
1 parente3c7c87 commit19492cb

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+
publicstaticclassSolution4 {
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+
publicvoidmoveZeroes(int[]nums) {
62+
inti =0;//zero index
63+
intj =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
privatestatic_283.Solution1solution1;
1212
privatestatic_283.Solution2solution2;
1313
privatestatic_283.Solution3solution3;
14+
privatestatic_283.Solution4solution4;
1415
privatestaticint[]nums;
1516

1617
@BeforeClass
1718
publicstaticvoidsetup() {
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(newint[]{1,1,0},nums);
126128
}
129+
130+
@Test
131+
publicvoidtest16() {
132+
nums =newint[]{2,1};
133+
solution4.moveZeroes(nums);
134+
assertArrayEquals(newint[]{2,1},nums);
135+
}
127136
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp