File tree 2 files changed +55
-0
lines changed
2 files changed +55
-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 = ( asteroids ) => {
6
+ let stack = [ ] ;
7
+
8
+ for ( asteroid of asteroids ) {
9
+ while ( stack . length != 0 && asteroid < 0 && stack . at ( - 1 ) > 0 ) {
10
+ let diff = asteroid + stack . at ( - 1 ) ;
11
+
12
+ if ( diff < 0 ) {
13
+ stack . pop ( ) ;
14
+ } else if ( diff > 0 ) {
15
+ asteroid = 0 ;
16
+ } else {
17
+ asteroid = 0 ;
18
+ stack . pop ( ) ;
19
+ }
20
+ }
21
+
22
+ if ( asteroid ) {
23
+ stack . push ( asteroid ) ;
24
+ }
25
+ }
26
+
27
+ return stack ;
28
+ } ;
Original file line number Diff line number Diff line change
1
+ use std:: cmp:: Ordering ;
2
+
3
+ impl Solution {
4
+ pub fn asteroid_collision ( asteroids : Vec < i32 > ) -> Vec < i32 > {
5
+ let mut stack: Vec < i32 > = vec ! [ ] ;
6
+
7
+ for mut asteroid in asteroids {
8
+ while !stack. is_empty ( ) && asteroid < 0 && stack. last ( ) > Some ( & 0 ) {
9
+ let diff = asteroid + stack. last ( ) . unwrap ( ) ;
10
+ match diff. cmp ( & 0 ) {
11
+ Ordering :: Less => {
12
+ stack. pop ( ) ;
13
+ }
14
+ Ordering :: Greater => asteroid = 0 ,
15
+ Ordering :: Equal => {
16
+ asteroid = 0 ;
17
+ stack. pop ( ) ;
18
+ }
19
+ } ;
20
+ }
21
+ if asteroid != 0 {
22
+ stack. push ( asteroid) ;
23
+ }
24
+ }
25
+ stack
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments