题目链接
思路:栈
分析:要相撞,只有一种情况,就是两个行星方向是相向而行,也就是左边的向右走,右边的向左走。
这里使用栈来表示运行的行星,因为每次要相撞的话,也有个先后顺序,先判断栈顶和当前元素满足相撞情况吗。
并且相撞的结果也有三种,谁能撞赢,或者平局,也就是两个都消失。
1.栈顶的输了,那么出栈,栈内下一个继续去判断,直到不相撞或者栈内空为止。
2.当前元素输了,那么当前元素不用入栈。
3.平局,那么栈顶元素出栈,并且当前元素也不用入栈。
遍历完所有元素以后,还在栈内的就是不会相撞的,也就是结果。
代码:
class Solution {
public int[] asteroidCollision(int[] asteroids) {
int len = asteroids.length;
int[] stack = new int[len];
int top = -1;
for(int i = 0 ; i < len; i++){
//栈不为空 并且栈顶元数向右 当前元数向左 并且 栈顶元数的绝对值小于当前元素的当前值 --------出栈
while(top!=-1 && stack[top]>0 && asteroids[i]<0 && Math.abs(stack[top])<Math.abs(asteroids[i])){
top--;
}
//栈不为空 并且栈顶元数向右 当前元数向左 并且 栈顶元数的绝对值等于当前元素的当前值 --------出栈并且当前元素也不入栈
if(top!=-1 && i<len && stack[top]>0 && asteroids[i]<0 && Math.abs(stack[top])==Math.abs(asteroids[i])){
top--;
continue;
}
//栈不为空 并且栈顶元数向右 当前元数向左 并且 栈顶元数的绝对值大于当前元素的当前值 -----当前元素不入栈
if(top!=-1 && stack[top]>0 && asteroids[i]<0 && Math.abs(stack[top])>Math.abs(asteroids[i])){
continue;
}
stack[++top]=asteroids[i];
}
if(top==-1){
return new int[]{};
}
int[] res = new int[top+1];
for(int i = 0 ; i < top+1;i++){
res[i] =stack[i];
}
return res;
}
}