-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsteroidCollision.cpp
38 lines (38 loc) · 1.04 KB
/
AsteroidCollision.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
class Solution {
public:
vector<int> asteroidCollision(vector<int>& arr) {
std::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
vector<int> res;
stack<int> st;
for(int i = 0; i<arr.size(); ){
int next = arr[i];
if(next > 0){
st.push(next);
i++;
}else{
if(st.empty() || (st.top()<0)){
st.push(next);
i++;
}else{
if(st.top() == abs(next)){
st.pop();
i++;
}else if(st.top() > abs(next)){
i++;
}else if(st.top() < abs(next)){
st.pop();
next = next;
}
}
}
}
while(!st.empty()){
res.push_back(st.top());
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
};