【栈】LeetCode 735. 行星碰撞
题目链接
思路
当分支情况太多的时候,使用 bool
变量来判断是否应该压入栈
代码
class Solution{
public int[] asteroidCollision(int[] asteroids){
Stack<Integer> stack = new Stack<>();
for(int aster : asteroids){
boolean alive = true;
while(alive && aster < 0 && !stack.isEmpty() && stack.peek() > 0){
alive = stack.peek() < -aster;
if(stack.peek() <= -aster){
stack.pop();
}
}
if(alive){
stack.push(aster);
}
}
int size = stack.size();
int[] ans = new int[size];
for(int i = size - 1; i >= 0; i--){
ans[i] = stack.pop();
}
return ans;
}
}