代码随想录算法训练营day49

1.接雨水

1.1 题目

https://leetcode.cn/problems/trapping-rain-water/description/

1.2 题解

class Solution {
public:
    int trap(vector<int>& height) 
    {
        int count = 0;
        stack<int> st;
        st.push(0);
        for (int i = 1; i < height.size(); i++)
        {
            while (!st.empty() && height[i] > height[st.top()])
            {
                int rightHeight = height[i];
                int middleHeight = height[st.top()];
                st.pop();
                if (!st.empty())
                {
                    int leftHeight = height[st.top()];

                    //计算长
                    int h = min(leftHeight, rightHeight) - middleHeight;
                    //计算宽
                    int w = i - st.top() - 1;

                    //计算雨水面积
                    int s = w * h;
                    count += s;
                }
                
            }
            st.push(i);
        }
        return count;
    }
};

2.柱状图中最大的矩形

2.1 题目

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

2.2 题解

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) 
    {
        stack<int> st;
        st.push(0);
        int result = 0;
        //前后添加0
        vector<int> tmp;
        tmp.push_back(0);
        for (const auto& i : heights)
        {
            tmp.push_back(i);
        }
        tmp.push_back(0);
        for (int i = 1; i < tmp.size(); i++)
        {
            while (!st.empty() && tmp[i] < tmp[st.top()])
            {
                //右边比他小的
                int h = tmp[st.top()];
                st.pop();
                if (!st.empty())
                {
                    int index = st.top();
                    int w = i - index - 1;
                    int s = w * h;
                    result = max(result, s);
                }
            }
            st.push(i);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值