Solution using STL stack in C++


#1

vector Solution::nextGreater(vector &A) {

int s = A.size();

vector<int> ans(s);
stack<int> stk;

ans[s-1] = -1;

if( s <= 1 )
    return ans;

stk.push(0);

for( int i=1; i<s; i++ ){
    
    while( !stk.empty() && A[i] > A[stk.top()] ){
        
        ans[stk.top()] = A[i];
        stk.pop();
    }
    
    stk.push(i);
}

while( !stk.empty() ){
    
    ans[stk.top()] = -1;
    stk.pop();
}

return ans;

}