代码随想录第五十五天打卡

42. 接雨水

接雨水这道题目是 面试中特别高频的一道题,也是单调栈 应用的题目,大家好好做做。

建议是掌握 双指针 和单调栈,因为在面试中 写出单调栈可能 有点难度,但双指针思路更直接一些。

在时间紧张的情况有,能写出双指针法也是不错的,然后可以和面试官在慢慢讨论如何优化。

代码随想录

class Solution {
public:
    int trap(vector<int>& height) {
        stack<int>st;
        int res=0;
        for (int i=0;i<height.size();i++){
            if (st.empty() || height[st.top()]>height[i])st.push(i);
            else{
                while(!st.empty() && height[st.top()]<height[i]){
                int mid=st.top();
                st.pop();
                if (!st.empty())res+=(i-st.top()-1)*(min(height[st.top()],height[i])-height[mid]);
                }
                st.push(i);
            }
        }
        return res;
    }
};

总结

把左边最大和右边最大就是要求面积的思路理清楚了其实后面实现就不难了。

84.  柱状图中最大的矩形

有了之前单调栈的铺垫,这道题目就不难了。

ongjiez代码随想录

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int>st;
        heights.insert(heights.begin(), 0); // 数组头部加入元素0
        heights.push_back(0); // 数组尾部加入元素0
        st.push(0);
        int res=0;
        for (int i=1;i<heights.size();i++){
            if (st.empty() || heights[st.top()]<heights[i])st.push(i);
            else{
                while (!st.empty() && heights[st.top()]>heights[i]){
                    int mid=st.top();
                    st.pop();
                    if (!st.empty())res=max(res,heights[mid]*(i-st.top()-1));
                    else res=max(res,heights[mid]*i);
                }
                st.push(i);
            }
        }
        return res;
    }
};

总结

我还在想怎么把栈剩余的元素给算上,原来在后面加上个0就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值