Advertisement
jayati

Asteroid Collision

May 5th, 2024
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> asteroidCollision(vector<int>& asteroids) {
  4.         stack<int> s;
  5.         for(int x:asteroids)
  6.         {
  7.             bool f=true;
  8.             if(x>0)
  9.             {
  10.                 s.push(x);
  11.             }
  12.             else
  13.             {
  14.                 while(!s.empty())
  15.                 {
  16.                     int y=s.top();
  17.                     if(y<0)
  18.                     {
  19.                         break;
  20.                     }
  21.                     else
  22.                     {
  23.                         if(x+y==0)
  24.                         {
  25.                             s.pop();
  26.                             f=false;;
  27.                             break;
  28.                         }
  29.                         else if(x+y<0)
  30.                         {
  31.                             s.pop();
  32.                         }
  33.                         else
  34.                         {
  35.                             f=false;
  36.                             break;
  37.                         }
  38.                     }
  39.  
  40.  
  41.                 }
  42.                 if(f)
  43.                 {
  44.                     s.push(x);
  45.                 }
  46.                
  47.             }
  48.         }
  49.         int n=s.size();
  50.         vector<int> ans(n);
  51.         for(int i=n-1; i>=0; i--){
  52.             ans[i]=s.top();
  53.             s.pop();
  54.         }
  55.         return ans;
  56.     }
  57. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement