|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(n) |
| 3 | + |
| 4 | +# We are given an array asteroids of integers representing asteroids in a row. |
| 5 | +# |
| 6 | +# For each asteroid, the absolute value represents its size, |
| 7 | +# and the sign represents its direction (positive meaning right, negative meaning left). |
| 8 | +# Each asteroid moves at the same speed. |
| 9 | +# |
| 10 | +# Find out the state of the asteroids after all collisions. |
| 11 | +# If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. |
| 12 | +# Two asteroids moving in the same direction will never meet. |
| 13 | +# |
| 14 | +# Example 1: |
| 15 | +# Input: |
| 16 | +# asteroids = [5, 10, -5] |
| 17 | +# Output: [5, 10] |
| 18 | +# Explanation: |
| 19 | +# The 10 and -5 collide resulting in 10. The 5 and 10 never collide. |
| 20 | +# Example 2: |
| 21 | +# Input: |
| 22 | +# asteroids = [8, -8] |
| 23 | +# Output: [] |
| 24 | +# Explanation: |
| 25 | +# The 8 and -8 collide exploding each other. |
| 26 | +# Example 3: |
| 27 | +# Input: |
| 28 | +# asteroids = [10, 2, -5] |
| 29 | +# Output: [10] |
| 30 | +# Explanation: |
| 31 | +# The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. |
| 32 | +# Example 4: |
| 33 | +# Input: |
| 34 | +# asteroids = [-2, -1, 1, 2] |
| 35 | +# Output: [-2, -1, 1, 2] |
| 36 | +# Explanation: |
| 37 | +# The -2 and -1 are moving left, while the 1 and 2 are moving right. |
| 38 | +# Asteroids moving the same direction never meet, so no asteroids will meet each other. |
| 39 | +# |
| 40 | +# Note: |
| 41 | +# - The length of asteroids will be at most 10000. |
| 42 | +# - Each asteroid will be a non-zero integer in the range [-1000, 1000]. |
| 43 | + |
| 44 | +class Solution(object): |
| 45 | + def asteroidCollision(self, asteroids): |
| 46 | + """ |
| 47 | + :type asteroids: List[int] |
| 48 | + :rtype: List[int] |
| 49 | + """ |
| 50 | + result = [] |
| 51 | + for asteroid in asteroids: |
| 52 | + while result and asteroid < 0 < result[-1]: |
| 53 | + if result[-1] < -asteroid: |
| 54 | + result.pop() |
| 55 | + continue |
| 56 | + elif result[-1] == -asteroid: |
| 57 | + result.pop() |
| 58 | + break |
| 59 | + else: |
| 60 | + result.append(asteroid) |
| 61 | + return result |
0 commit comments