File tree 1 file changed +40
-13
lines changed
scripts/algorithms/A/Asteroid Collision
1 file changed +40
-13
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public:
3
3
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
+
7
12
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);
12
35
}
13
- if (a) s.push (a);
14
36
}
15
37
}
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;
20
47
}
21
- };
48
+ };
You can’t perform that action at this time.
0 commit comments