[LeetCode] Asteroid Collision

735. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> res;
for(auto& a : asteroids) {
if(res.empty()) {
res.push_back(a);
continue;
}
bool f1, f2 = a > 0;
while(!res.empty()) {
f1 = res.back() > 0;
if((!f1 && f2) || (f1 == f2)) {res.push_back(a); break;}
else if(abs(res.back()) == abs(a)) {res.pop_back(); break;}
else if(abs(res.back()) > abs(a)) {break;}
else {
res.pop_back();
if(res.empty()) {
res.push_back(a);
break;
}
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/09/PS/LeetCode/asteroid-collision/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.