标签:leetcode
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.
我们使用最简单的两层for循环方法。对于每一个柱行图i的高度h,我们把i的宽度分别往左和右延展,求出每个点住状图左右延展后的最大矩形面积,然后取最大值。
左右延展的限制条件是:
i >= 0 && height[i] >= h
i < height.length && height[i] >= h
代码如下:
public class Solution {
public int largestRectangleArea(int[] height) {
if (height == null || height.length == 0) return 0;
int area = 0;
for (int i = 0; i < height.length; i++) {
int high = height[i];
int width = 1;
for (int j = i - 1; j >= 0 && height[j] >= high; j--) {
width++;
}
for (int j = i + 1; j < height.length && height[j] >= high; j++) {
width++;
}
area = Math.max(area, high * width);
}
return area;
}
}
不过,有个问题就是,这种做法在LeetCode上是没法通过大集合测试的,因为该算法的时间复杂度是O(n^2)。接下来,我们看一下,如何将O(n^2)的时间复杂度降低为O(n)。
这里介绍一种使用栈的O(n)解法。想要降低时间复杂度,必然相应的要增加空间复杂度了。
我们用栈存储height数组高度递增的下标。因为,对于每一个柱形图的高度来说,分为两种情况:
不为1的情况,则当前栈顶下标出栈,计算当前栈顶下标所代表高度的最大矩形。既然,高度已经已经确定,那宽度又分为两种情况(假设遍历点的下标为i):
AC代码
public class Solution {
public int largestRectangleArea(int[] height) {
if (height == null || height.length == 0) return 0;
int area = 0, len = height.length;
LinkedList<Integer> stack = new LinkedList<Integer>();
for (int i = 0; i < len; i ++) {
if (stack.isEmpty() || height[stack.peek()] <= height[i]) {
stack.push(i);
} else {
int index = stack.pop();
int high = height[index];
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
area = Math.max(area, high * width);
i -= 1;
}
}
while (!stack.isEmpty()) {
int index = stack.pop();
int high = height[index];
int width = stack.isEmpty() ? len : len - stack.peek() - 1;
area = Math.max(area, high * width);
}
return area;
}
}
[LeetCode]Largest Rectangle in Histgram,解题报告
标签:leetcode
原文地址:http://blog.csdn.net/wzy_1988/article/details/45218823