Skip to content

Commit 571ea1b

Browse files
committed
Complete Leetcode 735
1 parent 8d6e800 commit 571ea1b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Stack/735-AsteroidCollision/README.md

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Asteroid Collision
2+
3+
Problem can be found in [here](https://leetcode.com/problems/asteroid-collision/)!
4+
5+
### [Solution](/Stack/735-AsteroidCollision/solution.py): Stack
6+
7+
```python
8+
def asteroidCollision(asteroids: List[int]) -> List[int]:
9+
stack = []
10+
11+
for asteroid in asteroids:
12+
while stack and asteroid < 0 < stack[-1]:
13+
if stack[-1] + asteroid < 0:
14+
stack.pop()
15+
elif stack[-1] == -asteroid:
16+
stack.pop()
17+
break
18+
else:
19+
break
20+
else:
21+
stack.append(asteroid)
22+
23+
return stack
24+
```
25+
26+
Time Complexity: ![O(n)](<https://latex.codecogs.com/svg.image?\inline&space;O(n)>), Space Complexity: ![O(1)](<https://latex.codecogs.com/svg.image?\inline&space;O(1)>)
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
6+
stack = []
7+
8+
for asteroid in asteroids:
9+
while stack and asteroid < 0 < stack[-1]:
10+
if stack[-1] + asteroid < 0:
11+
stack.pop()
12+
elif stack[-1] == -asteroid:
13+
stack.pop()
14+
break
15+
else:
16+
break
17+
else:
18+
stack.append(asteroid)
19+
20+
return stack

0 commit comments

Comments
 (0)