[
stack
array
]
BinarySearch 0117 Space Battle
Problem statement
https://binarysearch.com/problems/Space-Battle/
Solution
Equal to Leetcode 0735. Asteroid Collision.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def solve(self, nums):
stack = []
for ast in nums:
stack.append(ast)
while len(stack) > 1 and stack[-1] < 0 and stack[-2] > 0:
if stack[-1] + stack[-2] < 0: stack.pop(-2)
elif stack[-1] + stack[-2] > 0: stack.pop()
else:
stack.pop(); stack.pop()
break
return stack