数字右边第一个大于它的数(单调栈)

维护一个单调递减的栈,在新数字压栈前,可能需要弹出旧数字,这个新数字就是弹出的旧数字右边第一个比他大的数字。

代码:

vector<int> func(vector<int>& v){
     
 vector<int> res(v.size(), -1);
 stack<int> st;
 st.push(0);
 for(int i = 1; i < len; i++){
     
  while(!st.empty() && v[i] > v[st.top()]){
     
   res[st.top()] = v[i];
   st.pop();
  }
  st.push(i);
 }
 return res;
}

你可能感兴趣的:(算法)