-
Notifications
You must be signed in to change notification settings - Fork 0
/
Asteroid Collision.cpp
56 lines (46 loc) · 1.76 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
class Solution {
public:
vector<int> asteroidCollision(vector<int>& ast) {
stack<int> store;
vector<int> result;
for(int i = 0 ; i < ast.size();i++){
//pushing the right moving asteroids in the stack , and we wait for the left moving ones to decide the collisions
if(store.empty() || ast[i] > 0){
store.push(ast[i]);
}
else{
while(true){
//what we will have here is a left moving or a negative asteroid
int top = store.top();
if(top < 0){
store.push(ast[i]);
break;
}
//checking if the colliding asteroids are equal
else if(top == abs(ast[i])){
store.pop();
//both are destroyed
break;
}
else if(top > abs(ast[i])){
break; //the right moving asteroid just crushed the left moving one
}
else{
//if we reach here, that means that it is a bigger asteroid
store.pop(); //it crushes the existing top
if(store.empty()){
store.push(ast[i]);
break;
}
}
}
}
}
while(!store.empty()){
result.emplace_back(store.top());
store.pop();
}
reverse(result.begin(), result.end()); //that is how stack is
return result;
}
};