File tree 1 file changed +66
-0
lines changed
1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < vector>
3
+ #include < stack>
4
+ #include < algorithm>
5
+
6
+ using namespace std ;
7
+
8
+ class Solution {
9
+ public:
10
+ vector<int > asteroidCollision (vector<int >& asteroids) {
11
+ stack<int > stk;
12
+
13
+ for (auto var : asteroids){
14
+ bool explode = false ;
15
+ // A collision can occur only when a left-moving asteroid (var < 0) meets a right-moving asteroid (stk.top() > 0).
16
+ while (!stk.empty () && var < 0 && stk.top () > 0 ){
17
+ if (stk.top () < -var){
18
+ stk.pop ();
19
+ continue ;
20
+ } else if (stk.top () == -var){
21
+ stk.pop ();
22
+ explode = true ;
23
+ break ;
24
+ } else {
25
+ explode = true ;
26
+ break ;
27
+ }
28
+ }
29
+ if (!explode){
30
+ stk.push (var);
31
+ }
32
+ }
33
+
34
+ vector<int > res (stk.size ());
35
+ for (int i = stk.size ()-1 ; i >= 0 ; --i){
36
+ res[i] = stk.top ();
37
+ stk.pop ();
38
+ }
39
+ return res;
40
+ }
41
+ };
42
+
43
+
44
+ int main (){
45
+ Solution sol;
46
+ vector<int > asteroids = {-2 ,-1 ,1 ,2 };
47
+ sol.asteroidCollision (asteroids);
48
+ return 0 ;
49
+ }
50
+
51
+ /*
52
+ stk.top() < -var:
53
+ Explanation: The right-moving asteroid on the stack is smaller than the left-moving asteroid (|stk.top()| < |var|).
54
+ Action: The right-moving asteroid is destroyed (stk.pop()).
55
+ continue;: Loop continues to check for further possible collisions with other right-moving asteroids on the stack.
56
+ stk.top() == -var:
57
+ Explanation: Both asteroids are of equal size (|stk.top()| == |var|).
58
+ Action: Both asteroids are destroyed.
59
+ stk.pop();: Remove the right-moving asteroid from the stack.
60
+ destroyed = true;: Mark the current left-moving asteroid as destroyed.
61
+ break;: Exit the while loop since the current asteroid is destroyed.
62
+ else:
63
+ Explanation: The right-moving asteroid on the stack is larger than the left-moving asteroid (|stk.top()| > |var|).
64
+ Action: The left-moving asteroid is destroyed (destroyed = true;).
65
+ break;: Exit the while loop since the current asteroid is destroyed.
66
+ */
You can’t perform that action at this time.
0 commit comments