Skip to content

Commit 55a1895

Browse files
committed
Runtime 17 ms (Top 47.11%) | Memory 17.0 MB (Top 73.6%)
1 parent 710f392 commit 55a1895

File tree

1 file changed

+40
-13
lines changed

1 file changed

+40
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,48 @@
11
class Solution {
22
public:
33
vector<int> asteroidCollision(vector<int>& asteroids) {
4-
stack<int> s;
5-
for(auto a: asteroids){
6-
if(s.empty()) s.push(a);
4+
5+
vector<int>v;
6+
stack<int>s;
7+
8+
for(auto x: asteroids){
9+
10+
if(x > 0) s.push(x);
11+
712
else{
8-
while(!s.empty() && a < 0 && s.top() * a < 0){
9-
if(abs(a) == abs(s.top())){ a = 0; s.pop(); }
10-
else if( abs(a) < abs(s.top())) a = 0;
11-
else s.pop();
13+
14+
// Case 1: whem top is less than x
15+
16+
while(s.size() > 0 && s.top() > 0 && s.top() < -x){
17+
s.pop();
18+
}
19+
20+
// case 2 : when both of same size
21+
if( s.size() > 0 && s.top()==-x) {
22+
s.pop();
23+
}
24+
25+
// case 3: when top is greater
26+
27+
else if( s.size() > 0 && s.top() > -x ){
28+
// do nothing
29+
}
30+
31+
// case 4: when same direction
32+
33+
else{
34+
s.push(x);
1235
}
13-
if(a) s.push(a);
1436
}
1537
}
16-
vector<int> ans;
17-
while(!s.empty()) { ans.push_back(s.top()); s.pop(); }
18-
reverse(ans.begin(), ans.end());
19-
return ans;
38+
39+
while(!s.empty()){
40+
v.push_back(s.top());
41+
s.pop();
42+
}
43+
44+
reverse(v.begin(),v.end());
45+
46+
return v;
2047
}
21-
};
48+
};

0 commit comments

Comments
 (0)