forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asteroid-collision.cpp
57 lines (50 loc) · 1.21 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int> s;
for(int i=0;i<asteroids.size();i++)
{
if(s.empty() or asteroids[i]>0)
{
s.push(asteroids[i]);
}
else
{
while(true)
{
int top = s.top();
if(top<0)
{
s.push(asteroids[i]);
break;
}
else if(top==-asteroids[i])
{
s.pop();
break;
}
else if(top>(-asteroids[i]))
{
break;
}
else
{
s.pop();
if(s.empty())
{
s.push(asteroids[i]);
break;
}
}
}
}
}
vector<int> output(s.size(),0);
for(int i=s.size()-1;i>=0;i--)
{
output[i]=s.top();
s.pop();
}
return output;
}
};