- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathday33_735.py
55 lines (51 loc) · 2.23 KB
/
day33_735.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
fromtypingimportList
classSolution:
defasteroidCollision(self, asteroids: List[int]) ->List[int]:
"""
利用栈来模拟
1. 空栈: 入栈
2. 栈顶方向左: 入栈
3. 栈顶方向右:
a. 相同方向: 入栈
b. 相反方向:
a. 栈顶 > 新行星: 跳过该行星
b. 栈顶 = 新行星: 出栈
c. 栈顶向右 < 新行星: 出栈, loop 3.c.
I.没有栈顶了: 入栈该行星
II. 栈顶向左: 入栈
III. 相等: 出栈
IIII. 栈顶>新行星: 跳过该行星
"""
iflen(asteroids) <2:
raiseKeyError
stack= []
forweightinasteroids:
ifnotstackorstack[-1] <0:
stack.append(weight)
else:
ifstack[-1] *weight>0:
stack.append(weight)
else:
ifstack[-1] >abs(weight):
continue
elifstack[-1] ==abs(weight):
stack=stack[:-1]
else:
whilestackandstack[-1] >0andstack[-1] <abs(weight):
stack=stack[:-1]
ifnotstackorstack[-1] <0:
stack.append(weight)
elifstack[-1] ==abs(weight):
stack=stack[:-1]
elifstack[-1] >abs(weight):
continue
returnstack
if__name__=="__main__":
assertSolution().asteroidCollision(asteroids=[5, 10, -5]) == [5, 10]
assertSolution().asteroidCollision(asteroids=[5, -5]) == []
assertSolution().asteroidCollision(asteroids=[10, 2, -5]) == [10]
assertSolution().asteroidCollision(asteroids=[2, 10, 2, -5]) == [2, 10]
assertSolution().asteroidCollision(asteroids=[2, -2, 10, 2, -5]) == [10]
assertSolution().asteroidCollision(asteroids=[-2, -1, 1, 2]) == [-2, -1, 1, 2]
assertSolution().asteroidCollision(asteroids=[-2, -2, 1, -2]) == [-2, -2, -2]
assertSolution().asteroidCollision(asteroids=[-2, -1, 1, -2]) == [-2, -1, -2]