在书上看到O(n)的算法
如果用分治的话复杂度为n*log(n)
首先在数组两端各加一个0,为了后面写代码方便而且不会影响最后计算出的结果
原题:
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.最大矩形的高一定与直方图某矩形块高度相同,证明也很简单
2.由1可以想到:求最大矩形面积可以转化为问题:求以直方图某矩形块高度作出的矩形中最大的矩形面积,比如对例子中的直方图,就是求高度为2、1、5、6、2、3的最大矩形面积。对于矩形块0号,其高度为2,对应的最大矩形宽度为1,面积为2;对于矩形块1号,其高度为1,对应的最大矩形宽度可为6,面积为6...这样原问题又转换为依次求各矩形块对应的最大矩形的宽度
3.假设A = [2 1 5 6 2 3]是直方图各矩形块高度,对于1号矩形块,暴力求对应的最大矩形宽度,从1号分别向左、向右搜索直到某矩形块高度小于1,这样可求出宽度为6;对每个矩形块对应的最大矩形都采用暴力的方法求宽度,时间复杂度会达到O^2。
4.我们可以设置一个堆栈,其中存储着高度递增的矩形块的下标,将复杂度降为O(n)。剩下的直接看代码理解吧。如果用分治算法的话复杂度会是O(nlogn)
public class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<Integer>();
int max_area = 0;
int idx = 0;
int left;
int height;
int area;
int i;
int[] new_heights = new int[heights.length+2];
new_heights[0] = 0;
for(i = 0; i<heights.length; ++i){
new_heights[i+1] = heights[i];
}
new_heights[i+1] = 0;
//0325
for(idx = 0; idx<(new_heights.length); ++idx){
while(!stack.isEmpty() && new_heights[idx]<new_heights[stack.peek()]){
height = new_heights[stack.pop()];
left = stack.peek();
if(!stack.isEmpty()){
area = height*(idx - left - 1);
}else{
area = height*idx;
}
if(max_area<area){
max_area = area;
}
}
stack.push(idx);
}
return max_area;
}
}