Open fockspaces opened 1 year ago
彗星只有在當 stack.top 為正, asteroid 為負時相撞:
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int> st;
for(int asteroid : asteroids) {
while(st.size() && st.top() > 0 && asteroid < 0) {
int diff = st.top() + asteroid;
if(diff < 0) st.pop();
else {
if(diff == 0) st.pop();
asteroid = 0; break;
}
}
if(asteroid) st.push(asteroid);
}
vector<int> ans(st.size());
for(int i = st.size() - 1; i >= 0; i--)
{ans[i] = st.top(); st.pop();}
return ans;
}
};
解法二:直接用 vector 做 stack 資料結構 省去 assign 時空間
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> st;
for(int asteroid : asteroids) {
while(st.size() && st.back() > 0 && asteroid < 0) {
int diff = st.back() + asteroid;
if(diff < 0) st.pop_back();
else {
if(diff == 0) st.pop_back();
asteroid = 0; break;
}
}
if(asteroid) st.push_back(asteroid);
}
return st;
}
};
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 <= 104 -1000 <= asteroids[i] <= 1000 asteroids[i] != 0 Accepted 282.6K