代码随想录训练营day49|单调栈part2

接雨水

力扣题目链接

class Solution {
public:
    int trap(vector<int>& height) {
        int h = 0;
        int result = 0;
        stack<int> st;//存index
        // st.push(0);
        for(int i = 0; i < height.size(); i++){
            if(!st.empty() && height[st.top()] <= height[i]){
                while(!st.empty() && height[st.top()] < height[i]){
                    h = height[st.top()];
                    st.pop();
                    if(!st.empty()){
                        int w = i-st.top()-1;
                        int h2 = min(height[st.top()], height[i])-h;
                        result += h2 * w;
                    }
                } 
            }
            st.push(i);
        }
        return result;
    }
};

柱状图中最大的矩形

力扣题目链接

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int result = 0;
        unordered_map<int, int> umap;
        stack<int> st;
        // 栈内元素递增
        for(int i = 0; i < heights.size(); i++){
            if(st.empty() || heights[st.top()] < heights[i]){
                st.push(i);
            }
            else{
                int j;
                // 遇到更小的元素时弹出,将入栈元素的index变为出栈的元素的,这里用覆盖heights来实现
                while(!st.empty() && heights[st.top()] >= heights[i]){
                    j = st.top();
                    // 判断局部矩阵
                    result = max(result, (i-j) * heights[j]);
                    heights[j] = heights[i];
                    st.pop();
                }
                st.push(j);
            }
        }
        // 将递增栈的元素弹出,栈内元素满足到heights.size()处为矩形
        while(!st.empty()){
            int j = heights.size();
            result = max(result, heights[st.top()] * (j - st.top()));
            st.pop();
        }
        return result;
    }
};
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值