-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0735-asteroid-collision.py
More file actions
27 lines (22 loc) · 728 Bytes
/
0735-asteroid-collision.py
File metadata and controls
27 lines (22 loc) · 728 Bytes
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
# time complexity: O(n)
# space complexity: O(n)
from typing import List
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
result = []
for asteroid in asteroids:
if asteroid > 0:
stack.append(asteroid)
else:
while len(stack) > 0 and stack[-1] < abs(asteroid):
stack.pop()
if len(stack) == 0:
result.append(asteroid)
else:
if stack[-1] == abs(asteroid):
stack.pop()
result += stack
return result
asteroids = [10, 2, -5]
print(Solution().asteroidCollision(asteroids))