您的位置:首页 > 其它

LeetCode刷题笔录Largest Rectangle in Histogram

2014-11-06 14:44 387 查看
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
.
我真的只会brute force的方法,就是对每一个height,遍历之前的所有height,计算一遍area。这里可以稍微prune一下,就是当height[i+1]>=height[i]时,最大面积一定不会以height[i]结尾,因此可以跳过height[i]。不过这样算法的时间复杂度还是O(n^2)
public class Solution {
public int largestRectangleArea(int[] height) {
if(height == null || height.length == 0)
return 0;
int maxArea = height[0];
for(int i = 1; i < height.length; i++){
if(i < height.length - 1 && height[i] <= height[i + 1])
continue;
int minHeight = height[i];
for(int j = i; j >= 0; j--){
minHeight = Math.min(height[j], minHeight);
maxArea = Math.max(maxArea, minHeight * (i - j + 1));
}
}

return maxArea;
}
}


O(n)的解法只能看大神的,确实神,不过不是很难理解。

可以知道每一个最大area一定会包含至少一个完整的hist。这样如果用这个完整的hist的高度去求面积,只要知道宽度就行了。如果现在有几个从左往右递增的高度,那么把这些index存到一个stack里。直到遇到第一个height小于stack顶元素的hist,则开始一个一个的pop出stack的元素并以当前stack顶元素作为最小的高度求面积。

看这里的解说吧,明白一些。

public class Solution {
public int largestRectangleArea(int[] height) {
if(height == null || height.length == 0)
return 0;
int maxArea = height[0];

Stack<Integer> s = new Stack<Integer>();
int i = 0;
while(i < height.length){
if(s.isEmpty() || height[i] >= height[s.peek()]){
s.push(i);
i++;
}
else{
int top = s.pop();
int area = height[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
maxArea = Math.max(maxArea, area);
}
}

while(!s.isEmpty()){
int top = s.pop();
int area = height[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
maxArea = Math.max(maxArea, area);

}

return maxArea;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: