forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asteroid-collision_1_AC.cpp
43 lines (39 loc) · 1018 Bytes
/
asteroid-collision_1_AC.cpp
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
42
43
#include <algorithm>
#include <vector>
using std::reverse;
using std::vector;
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
auto &a = asteroids;
int n = a.size();
vector<int> res;
if (n == 0) {
return res;
}
vector<int> st;
int i;
for (i = 0; i < n; ++i) {
if (a[i] < 0) {
while (!st.empty() && a[i] + st.back() < 0) {
st.pop_back();
}
if (st.empty()) {
res.push_back(a[i]);
continue;
}
if (a[i] + st.back() == 0) {
st.pop_back();
}
} else {
st.push_back(a[i]);
}
}
reverse(st.begin(), st.end());
while (!st.empty()) {
res.push_back(st.back());
st.pop_back();
}
return res;
}
};