按照降序的顺序将a数组的下标入栈
当压栈的元素大于栈顶的元素是意为找到元素
由于数组是循环的
遍历一趟之后,栈如果不空,需要再遍历一趟
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& a) {
stack<int> st;
vector<int>ret(a.size(),-1);
int n = a.size();
for(int i=0;i<n;i++){
if(st.empty()){
st.push(i);
}else{
if( a[i] <= a[st.top()] ){
st.push(i);
}else{
while(!st.empty() &&a[i] > a[st.top()]){
ret[st.top()] = a[i];
st.pop();
}
st.push(i);
}
}
}
for(int i=0;i<n;i++){
if( a[i] > a[st.top()] ){
while(!st.empty() &&a[i] > a[st.top()]){
ret[st.top()] = a[i];
st.pop();
}
}
}
return ret;
}
};