-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path735. Asteroid Collision.py
41 lines (32 loc) · 1.03 KB
/
735. Asteroid Collision.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""
Example 1:
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
"""
class Solution:
def asteroidCollision(self, asteroids: list[int]) -> list[int]:
stack = []
for asteroid in asteroids:
while stack and asteroid < 0 < stack[-1]:
if stack[-1] < -asteroid:
stack.pop()
continue
elif stack[-1] == -asteroid:
stack.pop()
break
else:
stack.append(asteroid)
return stack
example = Solution()
print(example.asteroidCollision([10, 2, -5]))
# example = Solution()
# print(example.asteroidCollision([10, 2, -5]))