[Leetcode]Largest Rectangle in Histogram - 非递减栈(递增及相等)

来源:互联网 发布:java web开发 编辑:程序博客网 时间:2024/04/29 12:52

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.


Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].


The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.

----------------------------------------------------------------------------------

解题思路:维护一个非递减栈,栈中存储元素的索引号。

1.当前元素height[i]大于等于栈顶元素时,进栈。

2.当前元素height[i]小于栈顶元素时,将栈顶元素topNum出栈,同时计算topNum*(i-1-s[top-1]) 

其中s[top-1]为栈中topNum前一个元素的索引号。

例如,当栈中已经有1,、5、6三个元素的索引号,height[4]=2这个元素要进栈时,这是topNum=6,

发现6>2,这时s[top-1]即为6在栈中的前一个元素5的索引号,也就是2,因为height[2]=5;

这时计算的就是6这一个元素的面积。但当6出栈后,topNum=5,依然大于height[4]=2,

这时s[top-1]=1,计算的面积就为5和6共同构成的面积了。

3.当遍历完整个height之后,如果栈中还有元素,还要一次把他们弹出来,并计算面积。

注:我在代码中的栈s[100000]及top,进栈是s[++top],就是s[0]这个元素没被用作栈中,而是作为栈空的一个判断。

当top==0,栈就为空了。

class Solution {public:    int largestRectangleArea(vector<int> &height) {        int len=height.size();        if(len==0) return 0;        int top=0,topNum,max=0,tmax=0;        s[0]=-1;        s[++top]=0;        for(int i=1;i<len;i++)        {            topNum=height[s[top]];            while(top>0&&topNum>height[i])            {                tmax=topNum*(i-s[top-1]-1);                if(tmax>max)                    max=tmax;                topNum=height[s[--top]];            }            s[++top]=i;        }        while(top>0)        {            tmax=height[s[top]]*(len-s[top-1]-1);            if(tmax>max) max=tmax;            --top;        }        return max;    }private:    int s[100000];};


0 0
原创粉丝点击