-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsteroidCollision.cpp
More file actions
31 lines (31 loc) · 840 Bytes
/
AsteroidCollision.cpp
File metadata and controls
31 lines (31 loc) · 840 Bytes
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
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int>st;
vector<int>res;
int i,sz=asteroids.size();
for(i=0;i<sz;i++)
{
if(asteroids[i]>0)
{
st.push(asteroids[i]);
}
else
{
while((!st.empty()) && (st.top()>0) && (st.top()<abs(asteroids[i])))
st.pop();
if((st.empty()) || (st.top()<0))
st.push(asteroids[i]);
else if((st.top()>0) && (st.top() == abs(asteroids[i])))
st.pop();
}
}
while(!st.empty())
{
res.push_back(st.top());
st.pop();
}
reverse(res.begin(),res.end());
return res;
}
};