[LintCode]Largest Rectangle in Histogram
Version 1 暴力
public class Solution {
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
public int largestRectangleArea(int[] height) {
// 2015-09-05 暴力 O(n^2)
if (height == null || height.length == 0) {
return 0;
}
int max = 0;
for (int i = 0; i < height.length; i++) {
int width = 1;
int curHeight = height[i];
int index = i;
while (index - 1 >= 0 && height[index - 1] >= curHeight) {
index--;
width++;
}
index = i;
while (index + 1 < height.length && height[index + 1] >= curHeight) {
index++;
width++;
}
max = Math.max(max, width * curHeight);
}
return max;
}
}
Version 2 利用栈 O(n)
public class Solution {
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
public int largestRectangleArea(int[] height) {
// 用到了栈这个数据结构
if (height == null || height.length == 0) {
return 0;
}
// 栈中放的是height数组的序号
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
int max = 0;
int len = height.length;
// 循环len + 1次,push len + 1次,pop len次
for (int i = 0; i <= len; i++) {
// 假设在height的最后加上一个值为-1的元素
int curtHeight = (i == len) ? -1 : height[i];
// i指向的元素和之前的元素比大小,下面<或者<=都可以
while (!stack.isEmpty() && curtHeight <= height[stack.peek()]) {
// 找到一个矩形,一定会pop一次,总共求len个矩阵
int hei = height[stack.pop()];
int wid = stack.isEmpty() ? i : i - stack.peek() - 1;
max = Math.max(max, hei * wid);
}
stack.push(i);
}
return max;
}
}