【代码随想录】day60

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、84柱状图中最大的矩形

做完接雨水后,这题确实不难了
指针法(超时后根据没通过的样例过滤):

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int res = 0;
        int n = heights.size();
        for (int i = 0; i < n; i ++) {
            if (heights[i] == 0 || heights[i] * n <= res || (i > 0 && heights[i] == heights[i-1])) {
                continue;
            }
            int maxLeft = i;
            int maxRight = i;
            while (maxLeft > 0 && heights[maxLeft -1] >= heights[i]) {
                maxLeft --;
            }
            while (maxRight < n - 1 && heights[maxRight + 1] >= heights[i]) {
                maxRight ++;
            }
            int tmp = heights[i] * (maxRight - maxLeft + 1);
            res = max(res, tmp); 
        }
        return res;
    }
};

单调栈法:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        heights.insert(heights.begin(), 0);
        heights.insert(heights.end(), 0);
        int n = heights.size();
        int res = 0;
        stack<int> st;
        st.push(0);
        for (int i = 1; i < n; i ++) {
            while (!st.empty() && heights[i] < heights[st.top()]) {
                int h = heights[st.top()];
                st.pop();
                if (!st.empty()) {
                    int w = i - st.top() - 1;
                    res = max(res, h * w);
                }
            }
            st.push(i);
        }
        return res;
    }
};


总结

代码随想录一刷结束!感觉真的学到了不少东西,之前虽然也做了四五百道题,但也没有这么系统刷过题。本次最大的收获是从代码随想录入门c++,希望一切的努力都能在日后有所收获。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值