首页 > 其他分享 >【栈】LeetCode 735. 行星碰撞

【栈】LeetCode 735. 行星碰撞

时间:2023-01-05 16:33:47浏览次数:72  
标签:peek int aster 碰撞 alive stack 735 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;
    }
}

标签:peek,int,aster,碰撞,alive,stack,735,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17027966.html

相关文章