Untitled
unknown
c_cpp
a year ago
1.4 kB
10
Indexable
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int> st;
for(int i=0 ; i<asteroids.size() ; i++) {
if(st.size() > 0) {
int newElement = asteroids[i];
while(!st.empty()) {
int atTop = st.top();
st.pop();
if((atTop >= 0 and newElement >= 0) or (atTop < 0 and newElement < 0) or (atTop < 0 and newElement >= 0)) {
st.push(atTop);
st.push(newElement);
break;
} else {
if(abs(newElement) > abs(atTop)) {
newElement = newElement;
}
else if (abs(newElement) < abs(atTop)) {
newElement = atTop;
}
else {
newElement = 1234567;
break;
}
}
}
if(st.empty() and newElement != 1234567) st.push(newElement);
} else {
st.push(asteroids[i]);
}
}
vector<int> ans;
while (!st.empty()) {
ans.push_back(st.top());
st.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};Editor is loading...
Leave a Comment