0735. Asteroid Collision (M)

Asteroid Collision (M)

题目

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.

Example 4:

Input: asteroids = [-2,-1,1,2]
Output: [-2,-1,1,2]
Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other. 

Constraints:

  • 1 <= asteroids <= 10^4
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0

题意

给定一个包含正数和负数的数组,正数代表会向右跑的行星,负数代表会向左的跑的行星。当两行星相遇,大尺寸的行星会撞碎小尺寸的,相同尺寸的都碎。问数组最后剩下的值。

思路

用栈实现:从左到右遍历,如果栈空或者是正数,则压入栈(正数只会向右跑,不会与已在栈中的发生碰撞);如果是负数,与栈顶比较,按情况判断: 1. 栈顶也是负数;2. 绝对值比栈顶大;3. 绝对值比栈顶小;4. 绝对值和栈顶相同;5. 栈空。


代码实现

Java

class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < asteroids.length; i++) {
            int cur = asteroids[i];
            if (stack.isEmpty() || cur > 0) {
                stack.push(cur);
            } else {
                boolean flag = true;
                while (!stack.isEmpty() && stack.peek() > 0 && -cur >= stack.peek()) {
                    if (-cur == stack.peek()) {
                        stack.pop();
                        flag = false;
                        break;
                    }
                    stack.pop();
                }
                if (flag && (stack.isEmpty() || stack.peek() < 0)) {
                    stack.push(cur);
                }
            }
        }

        int[] ans = new int[stack.size()];
        for (int i = stack.size() - 1; i >= 0; i--) {
            ans[i] = stack.pop();
        }
        return ans;
    }
}
posted @ 2020-10-22 10:40  墨云黑  阅读(124)  评论(0编辑  收藏  举报