###单调栈
所谓单调栈就栈中的元素都是单调的,就是单调性是一致的。不会出现波折。
比如说在
给定一个长度为 N 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 −1。
这道题中如果用暴力做法时间复杂度会非常高
如果说使用单调栈时间复杂度会降到线性的复杂度
首先单调栈用到了双指针的思想 , 我们从前往后读取数字 , 那么假如说 第3个数字x3 >x5,那么在读取下一个找左边最近的小于的数字一定不会找到x3,所以说就没有用,x3就可以删掉。
还有一种情况就是 如果读入的x小于 栈顶元素,那么下面读取的数字一定会先找到读取的x而不会找到后面的数字,此时我们只需要删掉栈顶元素,找到比x小的数字
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int stk[N] , n , tt ;
void push(int x)
{
stk[ ++ tt] = x;
}
void pop()
{
tt --;
}
bool empty_()
{
if (tt > 0) return false;
else return true;
}
int query()
{
return stk[tt];
}
int main()
{
cin>>n;
for (int i = 0 ; i < n ; i ++)
{
int x;
cin>>x;
if (empty_())
{
cout<<-1<<" ";
push(x);
}
else
{
//cout<<i<<endl;
while (query() >= x)pop();
if (empty_()) cout<<-1<<' ';
else if (query() < x) cout<<query()<<" ";
else cout<<-1<<" ";
push(x);
}
}
return 0;
}