LeetCode84 Largest Rectangle in Histogram 解题报告

Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

题意是:给一个连续的非负整数数组,求出该数组的直方图所能组成的面积最大的长方形。如图所示
LeetCode 84

这里解决思路就是维护一个栈s,如果栈顶的元素大于要push的元素,则直接推进来,否则就需要对栈不停地pop,同时更新result=max(result,count*s.top()), 直到栈顶的元素小于等于要push的元素。因为每次push的元素若大于栈顶的元素,后面栈pop可以直接计算到。若小于,则先计算栈里面所能组成的最大面积。

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) 
    {
        int re=0;
        stack<int> s;

        for(int i=0;i<heights.size();i++)
        {
            //当栈为空的时候,直接push
            if(s.empty())
            {
                s.push(heights[i]);
            }
            //当栈顶元素小于当前元素,直接push

            else if(s.top()<=heights[i])
            {
                s.push(heights[i]);
            }
            //当栈顶元素大于当前元素,需要对当前栈进行计算,同时重新push count个当前元素,count为pop的数量。
            else if(s.top()>heights[i])
            {
                int count=0;
                while(s.empty()==false&&s.top()>heights[i])
                {
                    count++;
                    re=max(re,count*s.top());
                    s.pop();
                }
                for(int j=0;j<=count;j++)
                {
                    s.push(heights[i]);
                }
            }
        }

        int count=0;
        while(s.empty()==false)
        {
            count++;
            re=max(re,count*s.top());
            s.pop();
        }

        return re;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值