735. Asteroid Collision
Description
We are given an array asteroids
of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Constraints
1 <= asteroids <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
Approach
Links
GeeksforGeeks
ProgramCreek
Examples
Input: asteroids = [5, 10, -5]
Output: [5, 10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Solutions
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public int[] asteroidCollision(int[] asteroids) {
if(asteroids == null || asteroids.length == 0) {
return new int[0];
}
Stack<Integer> stack = new Stack();
for(int asteroid: asteroids) {
if(asteroid < 0) {
while(!stack.isEmpty() && stack.peek() > 0 &&
stack.peek() < Math.abs(asteroid)) {
stack.pop();
}
if(!stack.isEmpty() && stack.peek() > 0) {
if(stack.peek() == Math.abs(asteroid)) {
stack.pop();
}
} else {
stack.push(asteroid);
}
} else {
stack.push(asteroid);
}
}
int[] state = new int[stack.size()];
for(int i = state.length-1; i >= 0; i--) {
state[i] = stack.pop();
}
return state;
}
}
Follow up
Last updated
Was this helpful?