File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -87,4 +87,37 @@ public int[] asteroidCollision(int[] asteroids) {
8787 return ans ;
8888 }
8989 }
90+
91+ public static class Solution3 {
92+ /**
93+ * My completely original solution on 1/14/2022.
94+ */
95+ public int [] asteroidCollision (int [] asteroids ) {
96+ Deque <Integer > stack = new LinkedList <>();
97+ for (int i = 0 ; i < asteroids .length ; i ++) {
98+ int a = 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+ } else if (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 = new int [stack .size ()];
117+ for (int i = ans .length - 1 ; i >= 0 ; i --) {
118+ ans [i ] = stack .pollLast ();
119+ }
120+ return ans ;
121+ }
122+ }
90123}
Original file line number Diff line number Diff line change 99public class _735Test {
1010 private static _735 .Solution1 solution1 ;
1111 private static _735 .Solution2 solution2 ;
12+ private static _735 .Solution3 solution3 ;
1213 private static int [] asteroids ;
1314 private static int [] expected ;
1415
1516 @ BeforeClass
1617 public static void setup () {
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 = new int []{5 , 10 };
2527 assertArrayEquals (expected , solution1 .asteroidCollision (asteroids ));
2628 assertArrayEquals (expected , solution2 .asteroidCollision (asteroids ));
29+ assertArrayEquals (expected , solution3 .asteroidCollision (asteroids ));
2730 }
2831
2932 @ Test
You can’t perform that action at this time.
0 commit comments