标签:
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
.
思路:计算以height[i]为最低点时的最大面积。
1. 创建一个栈stack;
1. 从头开始遍历数组,如果数组为空或者当前遍历元素height[i]>=stack.peek(),就将"i"进栈,注意是将"i"而不是height[i];
3. 如果height[i]<stack.peek();
计算以height[stack.pop()]为最短高度,长度为i-stack.peek()-1的面积;
如果此时stack为空,则长度为"i";
如果计算得到的面积大,则更新当前最大面积max;
4. 当遍历到数组结束时,添加一个元素“0”作为终点判断。
代码如下:
public int largestRectangleArea(int[] height) { if(height == null || height.length < 1) return 0; Stack<Integer> stack = new Stack<Integer>(); int max = 0; int current = 0; for(int i=0; i<=height.length;) { if(i == height.length) { current = 0; } else { current = height[i]; } if(stack.isEmpty() || current >= height[stack.peek()]) { stack.push(i); i++; } else { int h = height[stack.pop()]; int length = (stack.isEmpty() ? i : i-stack.peek()-1); max = Math.max(max, h*length); } } return max; }
LeetCode-84 Largest Rectangle in Histogram
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4345848.html