题目传送地址:​​https://leetcode.cn/problems/largest-rectangle-in-histogram/submissions/​

运行效率

Leetcode84. 柱状图中最大的矩形_职场和发展


代码如下:

//哨兵模式+ 单调栈解法

单调栈思路:​​https://leetcode.cn/problems/largest-rectangle-in-histogram/solution/zhu-zhuang-tu-zhong-zui-da-de-ju-xing-by-leetcode-/​

class Solution {
//使用了哨兵,目的是为了确保栈底始终有一个元素,那就是0
public static int largestRectangleArea(int[] heights) {
int maxArea = 0;
int[] array = new int[heights.length + 2];
System.arraycopy(heights, 0, array, 1, heights.length);
Stack<Integer> stack = new Stack<>();
//单调栈解法
for (int i = 0; i < array.length; i++) {
if (!stack.isEmpty()) {//如果栈不为空
Integer peek = stack.peek(); //查看栈顶元素
//如果栈顶元素的高度大一些
if (array[peek] > array[i]) {
stack.pop();//弹出栈顶元素
int width;
if (!stack.isEmpty()) { //如果接下来栈内还有元素
Integer left = stack.peek();
width = i - left - 1;
} else { //如果接下来栈内没有元素了
width = heights.length - 2;
}
int area = array[peek] * width;
maxArea = Math.max(maxArea, area);
i = i - 1;
} else { //如果栈顶元素的高度小一些
stack.push(i);
}
} else {
stack.push(i);
}
}
return maxArea;
}

}