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

Commit9dc51ae

Browse files
add a solution for 735
1 parent6ca65e6 commit9dc51ae

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_735.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,37 @@ public int[] asteroidCollision(int[] asteroids) {
8787
returnans;
8888
}
8989
}
90+
91+
publicstaticclassSolution3 {
92+
/**
93+
* My completely original solution on 1/14/2022.
94+
*/
95+
publicint[]asteroidCollision(int[]asteroids) {
96+
Deque<Integer>stack =newLinkedList<>();
97+
for (inti =0;i <asteroids.length;i++) {
98+
inta =asteroids[i];
99+
if (a >0) {
100+
stack.addLast(a);
101+
}else {
102+
if (!stack.isEmpty() &&stack.peekLast() >0) {
103+
if (stack.peekLast() >Math.abs(a)) {
104+
continue;
105+
}elseif (stack.peekLast() ==Math.abs(a)) {
106+
stack.pollLast();
107+
}else {
108+
stack.pollLast();
109+
i--;
110+
}
111+
}else {
112+
stack.addLast(a);
113+
}
114+
}
115+
}
116+
int[]ans =newint[stack.size()];
117+
for (inti =ans.length -1;i >=0;i--) {
118+
ans[i] =stack.pollLast();
119+
}
120+
returnans;
121+
}
122+
}
90123
}

‎src/test/java/com/fishercoder/_735Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@
99
publicclass_735Test {
1010
privatestatic_735.Solution1solution1;
1111
privatestatic_735.Solution2solution2;
12+
privatestatic_735.Solution3solution3;
1213
privatestaticint[]asteroids;
1314
privatestaticint[]expected;
1415

1516
@BeforeClass
1617
publicstaticvoidsetup() {
1718
solution1 =new_735.Solution1();
1819
solution2 =new_735.Solution2();
20+
solution3 =new_735.Solution3();
1921
}
2022

2123
@Test
@@ -24,6 +26,7 @@ public void test1() {
2426
expected =newint[]{5,10};
2527
assertArrayEquals(expected,solution1.asteroidCollision(asteroids));
2628
assertArrayEquals(expected,solution2.asteroidCollision(asteroids));
29+
assertArrayEquals(expected,solution3.asteroidCollision(asteroids));
2730
}
2831

2932
@Test

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp