1
1
package com .fishercoder .solutions ;
2
2
3
- import java .util .Stack ;
3
+ import java .util .Deque ;
4
+ import java .util .LinkedList ;
4
5
5
6
public class _735 {
6
7
public static class Solution1 {
7
8
public int [] asteroidCollision (int [] asteroids ) {
8
- Stack <Integer > stack = new Stack ();
9
+ Deque <Integer > stack = new LinkedList <> ();
9
10
for (int i = 0 ; i < asteroids .length ; i ++) {
10
11
if (!stack .isEmpty () && stack .peek () > 0 && asteroids [i ] < 0 ) {
11
12
if (Math .abs (stack .peek ()) < Math .abs (asteroids [i ])) {
@@ -27,7 +28,7 @@ public int[] asteroidCollision(int[] asteroids) {
27
28
return result ;
28
29
}
29
30
30
- private void collide (Stack <Integer > stack ) {
31
+ private void collide (Deque <Integer > stack ) {
31
32
do {
32
33
Integer top = stack .pop ();
33
34
if (!stack .isEmpty () && stack .peek () * top < 0 ) {
@@ -47,4 +48,43 @@ private void collide(Stack<Integer> stack) {
47
48
} while (!stack .isEmpty ());
48
49
}
49
50
}
51
+
52
+ public static class Solution2 {
53
+ /**
54
+ * My completely original solution on 11/5/2021.
55
+ */
56
+ public int [] asteroidCollision (int [] asteroids ) {
57
+ Deque <Integer > stack = new LinkedList <>();
58
+ for (int a : asteroids ) {
59
+ if (a > 0 ) {
60
+ stack .addLast (a );
61
+ } else {
62
+ if (!stack .isEmpty () && stack .peekLast () > 0 ) {
63
+ if (stack .peekLast () > Math .abs (a )) {
64
+ continue ;
65
+ } else if (stack .peekLast () == Math .abs (a )) {
66
+ stack .pollLast ();
67
+ } else {
68
+ while (!stack .isEmpty () && stack .peekLast () > 0 && stack .peekLast () < Math .abs (a )) {
69
+ stack .pollLast ();
70
+ }
71
+ if (!stack .isEmpty () && stack .peekLast () > 0 && stack .peekLast () == Math .abs (a )) {
72
+ stack .pollLast ();
73
+ continue ;
74
+ } else if (stack .isEmpty () || stack .peekLast () < 0 ) {
75
+ stack .addLast (a );
76
+ }
77
+ }
78
+ } else {
79
+ stack .addLast (a );
80
+ }
81
+ }
82
+ }
83
+ int [] ans = new int [stack .size ()];
84
+ for (int i = stack .size () - 1 ; i >= 0 ; i --) {
85
+ ans [i ] = stack .pollLast ();
86
+ }
87
+ return ans ;
88
+ }
89
+ }
50
90
}
0 commit comments