单调栈-----ACwing830找到每个数左边第一个比它小的数(存y)---(例题Leetcode084柱状图中最大的矩形)(例题既找左边也找右边,且存下标)

地址

https://www.acwing.com/problem/content/description/832/

描述

在这里插入图片描述

思想

在这里插入图片描述
在这里插入图片描述

动态过程

在这里插入图片描述

代码模板

#include <iostream>
#include <stack>
using namespace std;
const int N=1e5+10;
int a[N];
stack<int> s;
int main(){
    
    
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
    
    
        int t;cin>>t;
        while(!s.empty()&&t<=s.top()) s.pop();
        if(s.empty()) a[i]=-1;
        else a[i]=s.top();
        s.push(t);
    }
    for(int i=0;i<n;i++) cout<<a[i]<<" ";
    return 0;
}

例题

https://leetcode-cn.com/problems/largest-rectangle-in-histogram/submissions/

描述

在这里插入图片描述

思想

在这里插入图片描述

代码

class Solution {
    
    
public:
    int largestRectangleArea(vector<int>& h) {
    
    
        int n=h.size();
        stack<int>s;//存放下标
        //left[i]存放i左边比h[i]小的柱子的最近下标。
        //right[i]存放i右边比h[i]小的柱子的最近下标。
        vector<int> left(n),right(n);
        //计算left
        for(int i=0;i<n;i++){
    
    
            while(!s.empty()&&h[i]<=h[s.top()]) s.pop();
            if(s.empty()) left[i]=-1;
            else left[i]=s.top();
            s.push(i);
        }
        //清空栈
        s=stack<int>();
        //计算right
        for(int i=n-1;i>=0;i--){
    
    
            while(!s.empty()&&h[i]<=h[s.top()]) s.pop();
            //!!!!注意!!!!
            //右边和左边不一样
            if(s.empty()) right[i]=n;
            else right[i]=s.top();
            s.push(i);
        }
        //计算最大面积
        int res=0;
        for(int i=0;i<n;i++){
    
    
            res=max(res,h[i]*(right[i]-left[i]-1));
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_52934831/article/details/121753758