这里写目录标题
单调栈
牛客链接:NC157 单调栈
设定初始解为二维数组,且都为-1;两个栈,用于从左到右和从右到左搜索最近位置;栈内存储的是搜索的下标,以从左到右为例:当前下标元素大于栈顶或者栈顶为空,将当前下标加入栈内;直到遇到比当前栈顶下标对应元素小的值后,开始依次退栈,并且栈顶元素下标的最近坐标为当前搜索的下标。搜索完毕,栈顶剩余元素则没有找到比其小的左边,默认为-1;
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @return int整型vector<vector<>>
*/
vector<vector<int> > foundMonotoneStack(vector<int>& nums) {
// write code here
int n = nums.size();
stack<int> l_to_r;
stack<int> r_to_l;
vector<vector<int>> ans(n,{-1,-1});
for(int i =0;i<n ;++i){
if(l_to_r.size() == 0 or nums[i] >= nums[l_to_r.top()]) //o - n-1从左到右搜索
l_to_r.push(i);
else{
while(l_to_r.size() > 0 && nums[i] < nums[l_to_r.top()])
{
ans[l_to_r.top()][1] = i;
l_to_r.pop();
}
l_to_r.push(i);
}
int j = n-1-i; //n-1 - 0 从右到左搜索
if(r_to_l.size() == 0 or nums[j] >= nums[r_to_l.top()])
r_to_l.push(j);
else{
while(r_to_l.size() > 0 && nums[j] < nums[r_to_l.top()])
{
ans[r_to_l.top()][0] = j;
r_to_l.pop();
}
r_to_l.push(j);
}
}
return ans;
}
};