-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasteroid_collision.cpp
40 lines (36 loc) · 1.16 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
class Solution {
public:
vector<int> asteroidCollision(vector<int>& arr) {
stack<int> s;
int n = arr.size();
for(int i=0;i<n;i++){
int flag=0;
while(!s.empty()&&s.top()>0&&arr[i]<0){
int a=abs(s.top());
int b=abs(arr[i]);
if(a>b){
flag=1;
break;
}
else if(a<b){
s.pop();
}
else{
flag=1;
s.pop();
break;
}
}
if(flag==0) s.push(arr[i]);
}
vector<int> res;
while(s.size()>0)
{
res.push_back(s.top());
s.pop();
}
if(res.size()==0) return res;
reverse(res.begin(),res.end());
return res;
}
};