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:
asteroids.length
<= 104asteroids[i]
<= 1000asteroids[i]
!= 0
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
Yen-Chi ChenThu, Jul 20, 2023
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;
}
MarsgoatThu, Jul 20, 2023
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進去的愚蠢行為改掉了。
MarsgoatThu, Jul 20, 2023