<p>We are given an array <code>asteroids</code> of integers representing asteroids in a row.</p>

<p>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.</p>

<p>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.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> asteroids = [5,10,-5]
<strong>Output:</strong> [5,10]
<strong>Explanation:</strong> The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> asteroids = [8,-8]
<strong>Output:</strong> []
<strong>Explanation:</strong> The 8 and -8 collide exploding each other.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> asteroids = [10,2,-5]
<strong>Output:</strong> [10]
<strong>Explanation:</strong> The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= asteroids.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-1000 &lt;= asteroids[i] &lt;= 1000</code></li>
	<li><code>asteroids[i] != 0</code></li>
</ul>

#include <vector>

using namespace std;

class Solution {
public:
    vector<int> asteroidCollision(vector<int>& asteroids) {
        vector<int> result;  // 使用 vector 來模擬堆疊的行為
        
        for (int ast : asteroids) {
            bool destroyed = false;

            // 處理左移動的情況
            while (!result.empty() && result.back() > 0 && ast < 0) {
                if (result.back() < -ast) {
                    result.pop_back();  // 將較小的小行星從 result 中移除
                } else if (result.back() == -ast) {
                    result.pop_back();  // 如果大小相等，兩個都被摧毀
                    destroyed = true;
                    break;
                } else {
                    destroyed = true;  // result.back() 比 ast 大，ast 被摧毀
                    break;
                }
            }
            
            if (!destroyed) {
                result.push_back(ast);  // 如果沒有被摧毀，將 ast 放入 result
            }
        }
        
        return result;  // 返回結果
    }
};

20400