-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
34 lines (32 loc) · 1.14 KB
/
main.py
File metadata and controls
34 lines (32 loc) · 1.14 KB
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
class Solution(object):
def asteroidCollision(self, asteroids):
''':type asteroids: List[int]
:rtype: List[int]
'''
stack = []
for num in asteroids:
element = num
if element > 0:
stack.append(element)
else:
# left direction
while len(stack) != 0 and stack[-1] > 0:
top_element = stack[-1]
# eliminate current node
if top_element > -element:
element = None
break
elif top_element == -element:
# eliminiate both
stack.pop()
element = None
break
else:
# eliminate stack top. Then recursive check
stack.pop()
if element:
stack.append(element)
return stack
s = Solution()
print (s.asteroidCollision([5,10,-5])) # []
print (s.asteroidCollision([-2,-1,1,2])) # [-2,-1,1,2]