参考:https://zhidao.baidu.com/question/588429026434934405.html
/*
步骤:
1. 从左到右枚举所有元素,看看当前元素只有在负数(向左),栈顶是正数(向右)的时候才会撞(-> <-这样才会撞上),其余情况都是进栈等着被后续的行星撞。
2. 若能撞,当前元素直接把前面能撞的全部撞完,撞到不能撞或者自己被消灭为止。
3. 遍历完栈中的元素就是留下来(不相互冲突)的行星。
*/
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> s=new Stack<Integer>();
for(int i=0;i<asteroids.length;i++){
if(s.empty()) s.push(asteroids[i]);
else{
int temp=s.peek();
if(temp>0&&asteroids[i]<0) { //碰撞
if(temp<Math.abs(asteroids[i])){
while(s.empty()!=true&&s.peek()>0&&s.peek()<Math.abs(asteroids[i])){ //直到asteroids[i]不能再碰撞为止
s.pop();
}
if(s.empty()) s.push(asteroids[i]);
else if(s.peek()<0) s.push(asteroids[i]); //同方向情况
else if(s.peek()==Math.abs(asteroids[i])) s.pop(); //两者都消失的情况
}
else if(temp==Math.abs(asteroids[i])) s.pop(); //碰撞
}
else s.push(asteroids[i]);
}
}
int n=s.size();
int[] numbers=new int[n];
for(int i=n-1;i>=0;i--){
numbers[i]=s.pop();
}
return numbers;
}
}
679

被折叠的 条评论
为什么被折叠?



