题目:
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 heights = [2,1,5,6,2,3],
return 10.
思路:
1、暴力枚举法:用两重循环枚举所有可能的矩形,并求出面积最大者(注意在第二重循环时,需要记录下区间中的bar的最低值)。暴力法的时间复杂度是O(n^2)。一个稍微巧妙一些的做法是:对于每一个bar,以它为最低点,然后分别向左右两边延伸直到遇到比它更低的bar,此时开始计算面积。然而该方法的时间复杂度仍然是O(n^2)。
2、递增栈法:这是一个设计十分巧妙的方法,通过借助栈,可以将时间复杂度降低到O(n)。其思想是:维护一个元素递增的栈,这个栈保存了元素在数组中的位置。这样在栈中每一个左边的bar都比本身小,所以左边就天然有界了,也就是左边界就是左边的一个bar。遍历数组,做如下判断:
1)如果当前元素比栈顶元素小,则我们又找到了栈顶元素的右边界,因此我们在此时就可以计算以栈顶元素为最低bar的矩形面积了,因为左右边界我们都已经找到了。这样每出栈一个元素,即计算以此元素为最低点的矩形面积。当最终栈空的时候就计算出了以所有bar为最低点的矩形面积。
2)如果当前元素比栈顶元素大,那么直接入栈即可。
实现技巧:为保证让所有元素都出栈,需要首先在栈中压入一个0元素,因为一个元素要出栈,必须要要遇到一个比它小的元素。
代码:
递增栈法:
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
if(heights.size() == 0) {
return 0;
}
stack<int> s;
heights.push_back(0);
int sum = 0;
for(int i = 0; i < heights.size(); ++i)
{
if(s.empty() || heights[i] > heights[s.top()]) {
s.push(i);
}
else
{
int tmp = s.top();
s.pop();
// width is the key point to understand this algorithm
int width = s.empty() ? i : i - s.top() - 1;
sum = max(sum, heights[tmp] * width);
i--;
}
}
return sum;
}
};
本文介绍了一种高效求解直方图中最大矩形面积的问题,通过递增栈法将时间复杂度从O(n^2)降低到O(n)。以高度数组[2,1,5,6,2,3]为例,讲解了算法的具体实现步骤。

1392

被折叠的 条评论
为什么被折叠?



