-
Notifications
You must be signed in to change notification settings - Fork 0
/
Asteroid Collision.cpp
43 lines (43 loc) · 1.09 KB
/
Asteroid Collision.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
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
int n=asteroids.size();
stack<int> st;
vector<int> ans,v;
for(int i=0;i<n;i++)
{
if(asteroids[i]>=0)
st.push(asteroids[i]);
else if(asteroids[i]<0)
{
int f=0;
while(st.size()>0)
{
if(st.top()<abs(asteroids[i]))
{
st.pop();
}
else if(st.top()==abs(asteroids[i]))
{
st.pop();
f=1;
break;
}
else
break;
}
if(st.size()==0&&f==0)
ans.push_back(asteroids[i]);
}
}
while(st.size())
{
v.push_back(st.top());
st.pop();
}
reverse(v.begin(),v.end());
for(auto it:v)
ans.push_back(it);
return ans;
}
};