712175. Asteroid Collision
Asteroid Collision
Summary
Given a list of asteroids and their positions, determine which asteroids will collide with each other. Two asteroids are considered to collide if they have the same position in space.
This problem involves understanding the concept of stacks and arrays, as well as using these data structures to solve the problem efficiently.
Detailed Explanation
The asteroid collision problem can be solved by treating the list of asteroids as a stack. We iterate over the list from right to left, considering each asteroid's position. If an asteroid is about to collide with the one above it (i.e., they have the same position), we remove the top asteroid from the stack until there are no more collisions.
Here is a step-by-step breakdown of the solution:
- Initialize an empty stack.
- Iterate over the list of asteroids from right to left.
- For each asteroid, check if it will collide with the one above it (i.e., they have the same position).
- If a collision is detected, remove the top asteroid from the stack until there are no more collisions.
- Once all asteroids have been processed, the remaining asteroids in the stack represent those that will not collide.
Time complexity: O(n), where n is the number of asteroids. Space complexity: O(1), as we only use a constant amount of space to store the stack.
Optimized Solutions
Java
import java.util.Stack;
public class AsteroidCollision {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int i = asteroids.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && Math.abs(asteroids[i]) != Math.abs(stack.peek())) {
if (Math.abs(asteroids[i]) > Math.abs(stack.pop())) {
stack.push(asteroids[i]);
break;
} else if (Math.abs(asteroids[i]) < Math.abs(stack.peek())) {
break;
}
} else {
stack.push(asteroids[i]);
}
}
int[] result = new int[stack.size()];
for (int i = 0; i < result.length; i++) {
result[i] = stack.pop();
}
return result;
}
}