-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path735.cpp
More file actions
42 lines (41 loc) · 1.54 KB
/
Copy path735.cpp
File metadata and controls
42 lines (41 loc) · 1.54 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> s;
for (auto a : asteroids) {
if (a > 0) {
s.push_back(a);
}
else {
// consider a as the incoming asteroid, and the stack
// as the existing stable asteroid order.
while (1) {
if (s.empty()) {
s.push_back(a);
break;
}
// destroy incoming asteroid only
else if ((s.back() > 0) && (abs(s.back()) > abs(a))) {
break;
}
// destroy existing asteroid
else if ((s.back() > 0) && (abs(s.back()) < abs(a))) {
s.pop_back();
}
// mad, destroy existing and incoming asteroid.
else if ((s.back() > 0) && (abs(s.back()) == abs(a))) {
s.pop_back();
break;
}
// existing is negative, no destruction
// incoming will live peacefully
else {
s.push_back(a);
break;
}
}
}
}
return s;
}
};