vivek_ragi

ASTEROID_COLLISIONS

Jun 19th, 2021 (edited)
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> asteroidCollision(vector<int>& arr) {
  4.         int n = arr.size();
  5.        
  6.         vector<int> ans;
  7.        
  8.         stack<int> st;
  9.        
  10.        
  11.         for(int i = 0; i < n; ++i) {
  12.             if(arr[i] > 0) {
  13.                 st.push(arr[i]);
  14.             }
  15.            
  16.             else {
  17.                 while(!st.empty() and arr[i] < 0 and st.top() < abs(arr[i])) {
  18.                     st.pop();
  19.                 }
  20.                 if(st.empty()) {
  21.                     ans.push_back(arr[i]);
  22.                 }
  23.                 else if(st.top() == abs(arr[i])) {
  24.                     st.pop();
  25.                 }
  26.             }
  27.         }
  28.        
  29.         //reverse stack and push to ans
  30.        
  31.         stack<int> rev;
  32.        
  33.        
  34.         while(!st.empty()) {
  35.             rev.push(st.top());
  36.             st.pop();
  37.         }
  38.        
  39.         while(!rev.empty()) {
  40.             ans.push_back(rev.top());
  41.             rev.pop();
  42.         }
  43.         // reverse(ans.begin(), ans.end());
  44.         return ans;
  45.     }
  46. };
Add Comment
Please, Sign In to add comment