leetcode-Largest Rectangular Area in a Histogram

来源:互联网 发布:淘宝宝贝图片拍摄技巧 编辑:程序博客网 时间:2024/06/01 21:50

这篇文章提出了一个线性的解法,在这里翻译一下。同时也给自己加强下印象。

题目是这样的:

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.

原文中关键思想是:

For every bar ‘x’, we calculate the area with ‘x’ as the smallest bar in the rectangle. If we calculate such area for every bar ‘x’ and find the maximum of all areas, our task is done.

(对每一个柱子x,我们计算以它为最矮的一群紧挨着的柱子构成的矩形的面积。 那么如果我们对每一个柱子x都计算了这样的面积,其中最大的面积就是我们所求的)。思想是如此的简单!!可是,问题是,How to calculate area with ‘x’ as smallest bar? (如何计算这些面积呢?)

Poster继续分析:We need to know index of the first smaller (smaller than ‘x’) bar on left of ‘x’ and index of first smaller bar on right of ‘x’. Let us call these indexes as ‘left index’ and ‘right index’ respectively.(我们需要知道从柱子x往左边数,第一个比它小的柱子的序号,叫left index;以及从柱子x往右边数的第一个比它小的柱子的序号,叫right index)。怎么做呢?用栈!

We traverse all bars from left to right, maintain a stack of bars. Every bar is pushed to stack once. A bar is popped from stack when a bar of smaller height is seen. When a bar is popped, we calculate the area with the popped bar as smallest bar. How do we get left and right indexes of the popped bar – the current index tells us the ‘right index’ and index of previous item in stack is the ‘left index’.

(我们从左往右遍历,维护一个栈,栈中存放的是柱子们的序号。每一个柱子都被push一次。当栈顶的柱子比当前遍历到的柱子矮的时候,就把它出栈。这里是关健,对每一个出栈的柱子(准确的说是它的序号),计算之前提到的面积,即以它为最矮的一群紧挨着的柱子构成的最大面积。至于left index和right index,则分别是栈中与出栈柱子紧挨着的柱子以及当前遍历到的柱子(这里需要自己做一些理解))。

下面是算法的较为形式化的描述:

1) Create an empty stack.

(创建一个空栈)

2) Start from first bar, and do following for every bar ‘hist[i]‘ where ‘i’ varies from 0 to n-1.

(从第一个柱子开始,重复下面的事情)
……a) If stack is empty or hist[i] is higher than the bar at top of stack, then push ‘i’ to stack.

(如果栈空或者当前遍历的柱子比栈顶的柱子要高,则将当前遍历的柱子的序号压栈)
……b) If this bar is smaller than the top of stack, then keep removing the top of stack while top of the stack is greater. Let the removed bar be hist[tp]. Calculate area of rectangle with hist[tp] as smallest bar. For hist[tp], the ‘left index’ is previous (previous to tp) item in stack and ‘right index’ is ‘i’ (current index).

(如果遍历到的柱子要比栈顶的柱子矮,则开始连续的出栈,直到栈顶的柱子要比当前遍历的柱子高。对于每一个出栈的柱子,计算前面提到的面积。)

3) If the stack is not empty, then one by one remove all bars from stack and do step 2.b for every removed bar.

(如果最后栈非空(最简单的情形,当柱子是依次升高时,最后栈必然是非空),则持续的出栈,同时对出栈的柱子计算面积)。


代码我就不往这里贴了,原文里面有

0 0
原创粉丝点击