23.07.20 Today’s Leetcode
735. Asteroid Collision (medium)
My own solution, Dirty!!!
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
def help(arr):
res = []
i = 0
n = len(arr)
while i < n - 1:
a, b = arr[i], arr[i + 1]
if a > 0 and b < 0:
if abs(a) < abs(b):
res.append(b)
if abs(a) > abs(b):
res.append(a)
i += 1
else:
res.append(a)
i += 1
if i == n - 1:
res.append(arr[-1])
return res
res = asteroids[:]
prev = len(res)
for i in range(prev):
res = help(res)
temp = min(len(res), prev)
if prev == temp:
break
prev = temp
return res
with Stack
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for a in asteroids:
while stack and a < 0 and stack[-1] > 0:
diff = a + stack[-1]
if diff < 0:
stack.pop()
elif diff > 0:
a = 0
else:
a = 0
stack.pop()
if a:
stack.append(a)
return stack