File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } asteroids
3
+ * @return {number[] }
4
+ */
5
+ const asteroidCollision = function ( asteroids ) {
6
+ const positive = [ ]
7
+ const res = [ ]
8
+ for ( let i = 0 ; i < asteroids . length ; i ++ ) {
9
+ if ( asteroids [ i ] > 0 ) {
10
+ positive . push ( i )
11
+ } else {
12
+ const negVal = asteroids [ i ] ;
13
+
14
+ while ( positive . length > 0 && asteroids [ positive [ positive . length - 1 ] ] + negVal < 0 ) {
15
+ asteroids [ positive [ positive . length - 1 ] ] = undefined
16
+ positive . pop ( )
17
+ }
18
+
19
+ if ( positive . length > 0 ) {
20
+ if ( asteroids [ positive [ positive . length - 1 ] ] + negVal > 0 ) {
21
+ asteroids [ i ] = undefined
22
+ } else if ( asteroids [ positive [ positive . length - 1 ] ] + negVal === 0 ) {
23
+ asteroids [ i ] = undefined
24
+ asteroids [ positive [ positive . length - 1 ] ] = undefined
25
+ positive . pop ( )
26
+ }
27
+ }
28
+ }
29
+ }
30
+ return asteroids . filter ( el => el !== undefined )
31
+ } ;
You can’t perform that action at this time.
0 commit comments