[735. Asteroid Collision](https://leetcode.com/problems/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.
```
**Constraints**:
* 2 <= `asteroids.length` <= 10^4^
* -1000 <= `asteroids[i]` <= 1000
* `asteroids[i]` != 0
### 解答
#### Python
```python=
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
ans = []
for m in asteroids:
while m < 0 and ans and ans[-1] > 0:
if abs(m) > ans[-1]:
ans.pop()
continue
elif abs(m) == ans[-1]:
ans.pop()
break
else:
ans.append(m)
return ans
```
> [name=Yen-Chi Chen][time=Thu, Jul 20, 2023]
#### Javascript
```javascript=
function asteroidCollision(asteroids) {
const stack = [asteroids[0]];
for (let i = 1; i < asteroids.length; i++) {
if (!stack.length) {
stack.push(asteroids[i]);
continue;
}
const a = stack.pop();
const b = asteroids[i];
if (isCollision(a, b)) {
if (Math.abs(a) > Math.abs(b)) {
stack.push(a);
} else if (Math.abs(a) < Math.abs(b)) {
i--; // 後面的把前面的撞掉就要往前再比
}
} else {
// 沒碰撞就重新加回
stack.push(a);
stack.push(b);
}
}
return stack;
}
function isCollision(a, b) {
if (a * b < 0 && a > b) return true;
return false;
}
```
> [name=Marsgoat][time=Thu, Jul 20, 2023]
```javascript=
function asteroidCollision2(asteroids) {
const stack = [asteroids[0]];
for (let i = 1; i < asteroids.length; i++) {
const a = stack[stack.length - 1];
const b = asteroids[i];
if (a > 0 && b < 0) {
if (a < -b) {
stack.pop();
i--;
} else if (a === -b) {
stack.pop();
}
} else {
stack.push(b);
}
}
return stack;
}
```
> 稍微改了一下,把pop出來又push進去的愚蠢行為改掉了。
> [name=Marsgoat][time=Thu, Jul 20, 2023]
### Reference
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)