735. Asteroid Collision

15 阅读1分钟

image.png

Stack

class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();

        for (int cur : asteroids) {
            // 当前cur是否存留
            boolean alive = true;
            // 只有top+, cur-,才会相遇
            while (!stack.isEmpty() && stack.peek() > 0 && cur < 0) {
                if (stack.peek() < -cur) {
                    stack.pop();
                    alive = true; // 存活 e.g. 2 <-> -4
                } else if (stack.peek() == -cur) {
                    stack.pop();
                    alive = false; // 俩全死 e.g. 2 <-> -2
                    break; // 结束
                } else {
                    alive = false; // cur死 e.g. 4 <-> -2
                    break;
                }

           }

           if (alive) {
                stack.push(cur);
           }
        }

        // reverse add
        int[] res = new int[stack.size()];
        for (int i = res.length - 1; i >= 0; i--) {
            res[i] = stack.pop();
        }
        return res;
    }
}