Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4dbf4ca

Browse files
author
hj.tian
committed
feat: add leetcode75 day33 735
feat: add leetcode75 day33 735
1 parent fba2efe commit 4dbf4ca

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎leetcode75/day33_735.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
6+
"""
7+
利用栈来模拟
8+
1. 空栈: 入栈
9+
2. 栈顶方向左: 入栈
10+
3. 栈顶方向右:
11+
a. 相同方向: 入栈
12+
b. 相反方向:
13+
a. 栈顶 > 新行星: 跳过该行星
14+
b. 栈顶 = 新行星: 出栈
15+
c. 栈顶向右 < 新行星: 出栈, loop 3.c.
16+
I.没有栈顶了: 入栈该行星
17+
II. 栈顶向左: 入栈
18+
III. 相等: 出栈
19+
IIII. 栈顶>新行星: 跳过该行星
20+
"""
21+
if len(asteroids) < 2:
22+
raise KeyError
23+
stack = []
24+
for weight in asteroids:
25+
if not stack or stack[-1] < 0:
26+
stack.append(weight)
27+
else:
28+
if stack[-1] * weight > 0:
29+
stack.append(weight)
30+
else:
31+
if stack[-1] > abs(weight):
32+
continue
33+
elif stack[-1] == abs(weight):
34+
stack = stack[:-1]
35+
else:
36+
while stack and stack[-1] > 0 and stack[-1] < abs(weight):
37+
stack = stack[:-1]
38+
if not stack or stack[-1] < 0:
39+
stack.append(weight)
40+
elif stack[-1] == abs(weight):
41+
stack = stack[:-1]
42+
elif stack[-1] > abs(weight):
43+
continue
44+
return stack
45+
46+
47+
if __name__ == "__main__":
48+
assert Solution().asteroidCollision(asteroids=[5, 10, -5]) == [5, 10]
49+
assert Solution().asteroidCollision(asteroids=[5, -5]) == []
50+
assert Solution().asteroidCollision(asteroids=[10, 2, -5]) == [10]
51+
assert Solution().asteroidCollision(asteroids=[2, 10, 2, -5]) == [2, 10]
52+
assert Solution().asteroidCollision(asteroids=[2, -2, 10, 2, -5]) == [10]
53+
assert Solution().asteroidCollision(asteroids=[-2, -1, 1, 2]) == [-2, -1, 1, 2]
54+
assert Solution().asteroidCollision(asteroids=[-2, -2, 1, -2]) == [-2, -2, -2]
55+
assert Solution().asteroidCollision(asteroids=[-2, -1, 1, -2]) == [-2, -1, -2]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /