-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathAsteroid Collision.cpp
48 lines (34 loc) · 1.14 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
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int>v;
stack<int>s;
for(auto x: asteroids){
if(x > 0) s.push(x);
else{
// Case 1: whem top is less than x
while(s.size() > 0 && s.top() > 0 && s.top() < -x){
s.pop();
}
// case 2 : when both of same size
if( s.size() > 0 && s.top()==-x) {
s.pop();
}
// case 3: when top is greater
else if( s.size() > 0 && s.top() > -x ){
// do nothing
}
// case 4: when same direction
else{
s.push(x);
}
}
}
while(!s.empty()){
v.push_back(s.top());
s.pop();
}
reverse(v.begin(),v.end());
return v;
}
};