-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollision.cpp
More file actions
32 lines (30 loc) · 921 Bytes
/
collision.cpp
File metadata and controls
32 lines (30 loc) · 921 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
32
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
int n = asteroids.size();
stack<int> stk;
for(int i = 0; i < n; i++){
if(stk.empty() || asteroids[i] > 0){
stk.push(asteroids[i]);
}else{
while(!stk.empty() && stk.top() > 0 && stk.top() < abs(asteroids[i])){
stk.pop();
}
if(!stk.empty() && stk.top() == abs(asteroids[i])){
stk.pop();
}else{
if(stk.empty() || stk.top() < 0){
stk.push(asteroids[i]);
}
}
}
}
vector<int> ans(stk.size(), 0);
int size = stk.size();
while(!stk.empty()){
ans[--size] = stk.top();
stk.pop();
}
return ans;
}
};