您的位置:首页 > 其它

[Leetcode] largest rectangle in histogram 直方图中最大的矩形

2017-08-16 14:44 756 查看

问题

给定一个数组height,储存各个矩形条的高。宽度为1。找出直方图的最大矩形。

思路

创建一个栈,用于储存数组的下标。对于数组的每个元素,

1. 如果栈为空,或height[i]大于等于height[栈顶元素],那么将矩形条i压入栈中.

2. 如果height[i]小于height[栈顶元素],那么将栈顶元素出栈,计算最大矩形的面积,高为height[temp],temp为刚才出栈的元素。如果此时栈非空,那么宽度为i-1-stack.peek();如果为空,则宽度为i.

3. 如果遍历的i等于arr.length。那么将栈中所有的元素都出栈,更新最大矩形的面积。

代码如下:

public static int largestRectangleArea(int[] height){
Stack<Integer> stack = new Stack<>();
int result = 0;
for(int i=0;i<=height.length;i++){
if(i == height.length){
while(!stack.isEmpty() ){
int temp = stack.pop();
result = Math.max(result, height[temp]*(stack.empty()?i:(i-stack.peek()-1)));
}
}
else if(stack.isEmpty() || height[stack.peek()] <= height[i]){
stack.push(i);
}else{
int temp = stack.pop();
result = Math.max(result, height[temp]*(stack.empty()?i:(i-stack.peek()-1)));
--i;
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: