leetcode笔记:Largest Rectangle in Histogram

来源:互联网 发布:吉永小百合知乎 编辑:程序博客网 时间:2024/06/06 01:29

Largest Rectangle in Histogram

 Total Accepted: 8795 Total Submissions: 42970My Submissions

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.

这道题想了良久,感觉没什么思路,看了leetcode大神们的代码,令人叹服……

还是做做笔记吧。

主要思路:我们知道,每个木板将对应多个包含自身的直方图面积,我们从中选取最大的一个面积。

以上题为例,height[1]对应的包含自身直方图面积集合为{1, 2, 3, 4, 5, 6 } ,我们只需要知道最大的面积 6 即可,其它的面积就不用考虑。

我们就比较所有height[i] 对应最大直方图面积,把整体最大的直方图面积记为maxArea。

分析到这,我们很明显的可以知道时间复杂度为O(n)。

现在关键问题就变为如何得到height[i]对应的最大直方图面积。

这里用一个栈s来保存之前的元素索引。

s为空时,直接让 i 栈;

当height[i]<height[s.top()]时,说明height[s.top()]对应的直方图面积不会再增加了,此时达到最大,可以出栈了;

当height[i]>=height[s.top()]时,说明height[s.top()]对应的直方图面积还是有潜力增加的哈,此时,i 入栈,++i 。

以上取 i 从 0 到 n-1 。

当 i 达到n 时,而 栈不为空,说明还有部分height中元素对应的最大直方图面积没有求出来……

于是,当栈不为空时,求 height[s.top()]对应最大直方图面积。

我整理思路后,重新写了一份代码,下面贴出代码吧

    int largestRectangleArea(vector<int> &height) {                if(height.empty()){            return 0;        }        stack<int> s;        int i=0, n=height.size(),maxArea=0,top=0;        while(i<n){            if(s.empty()||height[s.top()]<=height[i]){                s.push(i);                ++i;            }else{                top=s.top();                s.pop();                maxArea=max(maxArea,height[top]*(s.empty()?i:i-s.top()-1));            }        }        while(!s.empty()){            top=s.top();            s.pop();            maxArea=max(maxArea,height[top]*(s.empty()?n:n-s.top()-1));        }        return maxArea;    }


0 0
原创粉丝点击