Programming

Leetcode-735. Asteroid Collision

Leetcode-735. Asteroid Collision

We are given an array asteroids of integers representing asteroids in a row.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

Example 1:

Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2:

Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3:

Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.

<解題>


class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Deque<Integer> stack = new ArrayDeque<>();
        for(int a : asteroids){
            if(stack.isEmpty() || a * stack.peek() >0 || stack.peek()< 0 && a >0){ //直接加入stack: 空、同向、互相遠離
                stack.push(a);
            } else{
                boolean flag = true; //看a是否要入stack
                while(!stack.isEmpty() && a * stack.peek() <0){ //產生碰撞:一樣大,左小,右小
                    if(Math.abs(stack.peek()) == Math.abs(a)){
                        stack.pop();
                        flag = false;
                        break;
                    } else if (Math.abs(stack.peek()) < Math.abs(a)){
                        stack.pop();
                    } else {
                        flag = false;
                        break;
                    }
                } 

                if(flag == true) stack.push(a);
            }
        }
        int size = stack.size();
        int[] res = new int[size];
        int index = size - 1;
        while(stack.size() > 0){
            res[index--] = stack.pop(); 
        }

        return res;
    }
}

Time: O(n) Space: O(n)