题目链接:https://leetcode.com/problems/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.
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.
解题思路:
最初的想法是针对每一个元素都维护一个属于它的窗口,在窗口中取高度最小的值求其面积。在求解过程中遇到一大问题就是,如何快速求解乱序数组中的最小值。解决了之后发现,该算法超时!!!
看了大神的 blog 才发现自己用的是最蠢的暴力破解法。
就是对于每一个窗口,找到其中最低的高度,然后求面积,取其中最大的矩形面积。总共有n^2个窗口,找最低高度是O(n)的操作,所以复杂度是O(n^3)。
遂参考了大神的解法:http://blog.youkuaiyun.com/linhuanmars/article/details/20524507
方法一:
1. 从每一个bar往两边走,以自己的高度为标准,直到两边低于自己的高度为止
2. 然后用自己的高度乘以两边走的宽度得到矩阵面积
因为我们对于任意一个bar都计算了以自己为目标高度的最大矩阵,所以最好的结果一定会被取到。每次往两边走的复杂度是O(n),总共有n个bar,所以时间复杂度是O(n^2)。
方法二: 重点掌握
最后我们谈谈最优的解法,思路跟 32 Longest Valid Parentheses 比较类似,我们要维护一个栈,这个栈从低向上的高度是依次递增的,如果遇到当前bar高度比栈顶元素低,那么就出栈直到满足条件,过程中检测前面满足条件的矩阵。
关键问题就在于在出栈时如何确定当前出栈元素的所对应的高度的最大范围是多少。答案跟 32 Longest Valid Parentheses 中括号的范围相似。
1. 就是如果栈已经为空,说明到目前为止所有元素(当前下标元素除外)都比出栈元素高度要大(否则栈中肯定还有元素),所以矩阵面积就是高度乘以当前下标i。
2. 如果栈不为空,那么就是从当前栈顶元素的下一个到当前下标的元素之前都比出栈元素高度大(因为栈顶元素第一个比当前出栈元素小的)。
为了更好的理解该算法,参考下面链接,这个博主画图说明了该方法,更加清楚明了。
http://blog.youkuaiyun.com/doc_sgl/article/details/11805519
注意:
做题时要多做总结,类似的题目应该归纳思路。
代码实现:
public class Solution {
public int largestRectangleArea(int[] height) {
if(height == null || height.length == 0)
return 0;
LinkedList<Integer> stack = new LinkedList();
int local = 0;
int global = 0;
for(int i = 0; i < height.length; i ++) {
while(!stack.isEmpty() && height[stack.peek()] > height[i]) {
int j = stack.pop();
if(!stack.isEmpty())
local = height[j] * (i - stack.peek() - 1);
else
local = height[j] * i;
global = Math.max(global, local);
}
stack.push(i);
}
while(!stack.isEmpty()) {
int j = stack.pop();
if(!stack.isEmpty())
local = height[j] * (height.length - stack.peek() - 1);
else
local = height[j] * height.length;
global = Math.max(global, local);
}
return global;
}
}
94 / 94 test cases passed.
Status: Accepted
Runtime: 22 ms