Leetcode # 735. Asteroid Collision

https://leetcode.com/problems/asteroid-collision

Solution

Time Complexity: O(len(asteroids))
Space Complexity: O(len(asteroids))
(The input and output generally do not count towards the space complexity.)

class Solution:
  def asteroidCollision(self, asteroids: List[int]) -> List[int]:
    stack = []
    for a in asteroids:
      left = a
      while stack and left and stack[-1] > 0 and left < 0:
        last = stack.pop()
        left = None if abs(a) == abs(last) else (a if abs(a) > abs(last) else last)
      if left:
        stack.append(left)
    return stack
        

 

Last Updated on 2023/08/16 by A1go

目錄

目錄
Bitnami