单调栈优化

  • Post author:
  • Post category:其他


对于每一个数如何找到它左边比它小的第一个数?除去O(N^2)的直接做法

这样想,由于从左往右最小,如果此时已经找到一个比较小的数,那么从右边来的已经大的数其实是没有用的。因为左边已经有一个小的数的存在。所以要一直弹栈,直到前面的数都小于当前的数。

#include<iostream>
#include<stack>
using namespace std;
#define N 100005
int nums[N],res[N];

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++) cin>>nums[i];
    stack<int> st;
    for(int i=0;i<n;i++){
        while(!st.empty()&&st.top()>=nums[i]) st.pop();
        if(st.empty()) res[i] = -1;
        else res[i] = st.top();
        st.push(nums[i]);
    }
    for(int i=0;i<n;i++) cout<<res[i]<<" ";
}



版权声明:本文为wwxy1995原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。