735. Asteroid Collision

Noobnoob
1 min readApr 29, 2021

--

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.

I used Stack to maintain the state.

class Solution {
Stack<Integer> stk=new Stack<Integer>();

public int[] asteroidCollision(int[] asteroids) {

for (int i = 0; i < asteroids.length; i++) {
if(asteroids[i]<0){
handleLeft(asteroids[i]);
}else{
stk.push(asteroids[i]);
}
}
int [] toreturn= new int[stk.size()];
for (int i = toreturn.length-1; i >=0 ; i--) {
toreturn[i]=stk.pop();
}
return toreturn;
}

private void handleLeft(int asteroid) {
if(stk.isEmpty()||stk.peek()<0){
stk.push(asteroid);
}else{
Integer pop = stk.pop();
if(pop==-1*asteroid){
return;
}else{
int toPush = pop > Math.abs(asteroid) ? pop : asteroid;
if(toPush<0){
handleLeft(toPush);
}else{
stk.push(toPush);
}
}
}
}
}

Runtime: 3 ms, faster than 96.20% of Java online submissions for Asteroid Collision.

Memory Usage: 39.8 MB, less than 36.41% of Java online submissions for Asteroid Collision.

--

--

Noobnoob
Noobnoob

No responses yet