-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroid-Collision.cpp
More file actions
37 lines (36 loc) · 1.1 KB
/
Copy pathAsteroid-Collision.cpp
File metadata and controls
37 lines (36 loc) · 1.1 KB
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
// Leetcode 735
class Solution {
public:
bool isColliding(vector<int>& asteroids, int i, int j){
return asteroids[i] > 0 && asteroids[j] < 0;
}
vector<int> asteroidCollision(vector<int>& asteroids) {
int n = asteroids.size();
stack<int> st;
st.push(0);
for(int i=1; i<n; i++){
bool isInsert = true;
while(!st.empty() && isColliding(asteroids, st.top(), i)){
int leftHealth = abs(asteroids[st.top()]);
int rightHealth = abs(asteroids[i]);
if(leftHealth < rightHealth){
st.pop();
}else if(leftHealth > rightHealth){
isInsert = false;
break;
}else{
st.pop();
isInsert = false;
break;
}
}
if(isInsert) st.push(i);
}
vector<int> ans;
while(!st.empty()){
ans.push_back(asteroids[st.top()]); st.pop();
}
reverse(begin(ans), end(ans));
return ans;
}
};