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) {
87
87
return ans ;
88
88
}
89
89
}
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
+ }
90
123
}
Original file line number Diff line number Diff line change 9
9
public class _735Test {
10
10
private static _735 .Solution1 solution1 ;
11
11
private static _735 .Solution2 solution2 ;
12
+ private static _735 .Solution3 solution3 ;
12
13
private static int [] asteroids ;
13
14
private static int [] expected ;
14
15
15
16
@ BeforeClass
16
17
public static void setup () {
17
18
solution1 = new _735 .Solution1 ();
18
19
solution2 = new _735 .Solution2 ();
20
+ solution3 = new _735 .Solution3 ();
19
21
}
20
22
21
23
@ Test
@@ -24,6 +26,7 @@ public void test1() {
24
26
expected = new int []{5 , 10 };
25
27
assertArrayEquals (expected , solution1 .asteroidCollision (asteroids ));
26
28
assertArrayEquals (expected , solution2 .asteroidCollision (asteroids ));
29
+ assertArrayEquals (expected , solution3 .asteroidCollision (asteroids ));
27
30
}
28
31
29
32
@ Test
You can’t perform that action at this time.
0 commit comments