File tree 1 file changed +13
-17
lines changed
scripts/algorithms/A/Asteroid Collision
1 file changed +13
-17
lines changed Original file line number Diff line number Diff line change 1
- # Runtime: 217 ms (Top 12.45%) | Memory: 15.1 MB (Top 94.18%)
1
+ # Runtime: 103 ms (Top 70.1%) | Memory: 17.56 MB (Top 44.2%)
2
+
2
3
class Solution :
3
4
def asteroidCollision (self , asteroids : List [int ]) -> List [int ]:
4
-
5
- res = []
6
-
7
- for asteroid in asteroids :
8
-
9
- while len (res ) and asteroid < 0 and res [- 1 ] > 0 :
10
-
11
- if res [- 1 ] == - asteroid :
12
- res .pop ()
13
- break
14
- elif res [- 1 ] < - asteroid :
15
- res .pop ()
5
+ stack = []
6
+ for a in asteroids :
7
+ while stack and stack [- 1 ] > 0 > a :
8
+ if stack [- 1 ] < abs (a ):
9
+ stack .pop ()
16
10
continue
17
- elif res [- 1 ] > - asteroid :
18
- break
11
+ elif stack [- 1 ] == abs (a ):
12
+ stack .pop ()
13
+ break # this means asteroid must be destroyed (not add to stack in else statement below)
19
14
else :
20
- res .append (asteroid )
21
- return res
15
+ stack .append (a )
16
+
17
+ return stack
You can’t perform that action at this time.
0 commit comments