题目:
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.
本题是寻找最大的矩形框,一种比较直接的思路是遍历数组,当遇到比他大的就记录下来,当遇到小的则开始向前遍历直到遇到比它更小的并更新矩形面积。我们可以方便的使用stack作为前面元素的存储,代码入下:
public int largestRectangleArea(int[] height) {
int len = height.length;
Stack<Integer> s = new Stack<>();
int maxArea = 0;
for(int i = 0; i <= len; i++){
int h = (i == len ? 0 : height[i]);
if(s.isEmpty() || h >= height[s.peek()]){
s.push(i);
}else{
//如果比上一个元素小,则出栈并更新maxArea。并将i--,这样继续出栈,直到遇到比该元素小的数
int tp = s.pop();
maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}
但是这种方法使用栈作为存储遍历过数字的数据结构,效率较低,另外一种思路就是我们首先遍历数组,针对每一个元素获得其左右两侧第一个比该元素小的值。这样我们就获得了每个元素左能形成的最大矩阵。然后在遍历一次,我们就能获得最大值了。代码入下:
public static int largestRectangleArea1(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int[] lessFromLeft = new int[height.length]; // idx of the first bar the left that is lower than current
int[] lessFromRight = new int[height.length]; // idx of the first bar the right that is lower than current
lessFromRight[height.length - 1] = height.length;
lessFromLeft[0] = -1;
for (int i = 1; i < height.length; i++) {
int p = i - 1;
while (p >= 0 && height[p] >= height[i]) {
p = lessFromLeft[p];
}
lessFromLeft[i] = p;
}
for (int i = height.length - 2; i >= 0; i--) {
int p = i + 1;
while (p < height.length && height[p] >= height[i]) {
p = lessFromRight[p];
}
lessFromRight[i] = p;
}
int maxArea = 0;
for (int i = 0; i < height.length; i++) {
maxArea = Math.max(maxArea, height[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
}
return maxArea;
}
上面这种方法可以击败96%的用户,其优点在于先通过两次遍历获得每个元素的预知信息。此外,还在discuss上面找到了一种效率更高的方法,可以击败98%的用户,代码入下:
public int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) return 0;
return getMax(heights, 0, heights.length);
}
int getMax(int[] heights, int s, int e) {
if (s + 1 >= e) return heights[s];
int min = s;
boolean sorted = true;
for (int i = s; i < e; i++) {
if (i > s && heights[i] < heights[i - 1]) sorted = false;
if (heights[min] > heights[i]) min = i;
}
if (sorted) {
int max = 0;
for (int i = s; i < e; i++) {
max = Math.max(max, heights[i] * (e - i));
}
return max;
}
int left = (min > s) ? getMax(heights, s, min) : 0;
int right = (min < e - 1) ? getMax(heights, min + 1, e) : 0;
return Math.max(Math.max(left, right), (e - s) * heights[min]);
}