1
+ // Runtime: 120 ms (Top 34.05%) | Memory: 44.1 MB (Top 63.23%)
1
2
/**
2
3
* @param {number[] } asteroids
3
4
* @return {number[] }
4
5
*/
5
6
var asteroidCollision = function ( asteroids ) {
6
-
7
+
7
8
const s = [ ] ;
8
9
for ( let i = 0 ; i < asteroids . length ; i ++ ) {
9
10
const a = asteroids [ i ] ;
10
-
11
- // Negative asteroids to the left of the stack can be ignored.
11
+
12
+ // Negative asteroids to the left of the stack can be ignored.
12
13
// They'll never collide. Let's just add it to the answer stack and
13
14
// move on. I consider this a special case.
14
15
if ( ( s . length === 0 || s [ s . length - 1 ] < 0 ) && a < 0 ) {
15
16
s . push ( a ) ;
16
-
17
+
17
18
// If an asteroid a is positive (l to r), it may still collide with an
18
19
// a negative asteroid further on in the asteroids array
19
20
} else if ( a > 0 ) {
20
21
s . push ( a ) ;
21
-
22
- // a is negative. It can only collide with positive ones in
23
- // the stack. The following will keep on iterating
22
+
23
+ // a is negative. It can only collide with positive ones in
24
+ // the stack. The following will keep on iterating
24
25
// until it is dealt with.
25
26
} else {
26
27
const pop = s . pop ( ) ;
27
-
28
+
28
29
// positive pop beats negative a, so pick up pop
29
30
// and re-add it to the stack.
30
31
if ( Math . abs ( pop ) > Math . abs ( a ) ) {
31
32
s . push ( pop ) ;
32
-
33
+
33
34
// a has larger size than pop, so pop will get dropped
34
- // and we'll retry another iteration with the same
35
+ // and we'll retry another iteration with the same
35
36
// negative a asteroid and whatever the stack's state is.
36
37
} else if ( Math . abs ( pop ) < Math . abs ( a ) ) {
37
38
i -- ;
38
39
// magnitude of positive pop and negative a are the same
39
40
// so we can drop both of them.
40
- } else {
41
+ } else {
41
42
continue ;
42
43
}
43
44
}
44
45
}
45
-
46
- // The stack should be the answer
46
+
47
+ // The stack should be the answer
47
48
return s ;
48
-
49
- } ;
49
+
50
+ } ;
0 commit comments