LeetCode 735 - Asteroid Collision
Description
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
Example 1:
Input: asteroids = [10,2,-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
2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
思路分析
分析题目可知,使行星发生碰撞的条件只有一种:前一个行星与后一个行星相向而行,即\(asteroids[x]>0,asteroids[x+1]<0\).
当行星发生碰撞后,需要继续判断是否发生第二次碰撞,显然,我们可以使用栈解决这个问题。
代码实现
// C++
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> stack;
for (int i = 0; i < asteroids.size(); i++) {
if (stack.empty() == true) {
stack.push_back(asteroids[i]);
continue;
}
if (stack.back() > 0 && asteroids[i] < 0) {
bool isPush = false;
while (stack.empty() == false && stack.back() > 0 && asteroids[i] < 0) {
if (abs(stack.back()) > abs(asteroids[i])) {
isPush = false;
break;
}
else if (abs(stack.back()) < abs(asteroids[i])) {
stack.pop_back();
isPush = true;
// stack.push_back(asteroids[i]);
}
else if (abs(stack.back()) == abs(asteroids[i])) {
stack.pop_back();
isPush = false;
break;
}
}
if (isPush == true) {
stack.push_back(asteroids[i]);
}
}
else {
stack.push_back(asteroids[i]);
}
}
return stack;
}
};