您的位置:首页 > 其它

【直方图的最大面积】Largest Rectangle in Histogram

2014-04-05 17:30 330 查看
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
.
思路参考:http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html

public class Solution {
public int largestRectangleArea(int[] height) {

Stack<Integer> s = new Stack<Integer>();
int [] h = new int[height.length + 1];
h = Arrays.copyOf(height, height.length + 1);

int i = 0, area = 0;
while(i < h.length){
if(s.isEmpty() || h[i] >= h[s.peek()]){
s.push(i++);
}
else{
int t = s.pop();
int tArea = h[t] * (s.isEmpty() ? i : i-s.peek()-1);
area = Math.max(tArea, area);
}
}
return area;
}
}

解法二:穷举,时间复杂度O(n2)

转自:http://leetcodenotes.wordpress.com/2013/07/21/largest-rectangle-in-histogram/

穷举两个边界,但不是完全穷举,这里可以省掉一部分右右边界。对于i,如果A[i] <= A[i + 1],即当前递增,则无论对于哪个左边界,选i+1作为右边界都比选i作为右边界合适(宽本来就多一个,然后高还更高,所以肯定选右边的面积大)。所以就算i+1作为右边界的所有左边界配对就行,没必要算i作为右边界的了。所以递推下去,只有A[i] > A[i + 1]的时候,在递减,说明拿A[i]和拿A[i
+ 1]不一定谁大了,这时候算一下A[i]作为右边界的左边界所有可能,就是一个local peak。这题还有一个O(n)的解法,但是暂时懒的看了。下次再看。

public int largestRectangleArea(int[] height) {
int res = 0;
for (int i = height.length - 1; i >= 0; i--) {
if (i == height.length - 1 || height[i] > height[i + 1]) { //A[i] is a local peak
int min = Integer.MAX_VALUE;
for (int j = i; j >= 0; j--) {
min = Math.min(min, height[j]);
res = Math.max(res, (i - j + 1) * min);
}
}
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: