其他分享
首页 > 其他分享> > 单调栈

单调栈

作者:互联网

简介

实现伪代码

stack<int> st;
for (遍历这个数组)
{
	if (栈空 || 栈顶元素大于等于当前比较元素)
	{
		入栈;
	}
	else
	{
		while (栈不为空 && 栈顶元素小于当前元素)
		{
			栈顶元素出栈;
			更新结果;
		}
		当前数据入栈;
	}
}

举例

84. 柱状图中最大的矩形

基本思路

优化思路

优化后代码

class Solution {
    public int largestRectangleArea(int[] heights) {
        int[] tmp = new int[heights.length + 2];
        System.arraycopy(heights, 0, tmp, 1, heights.length); 
        int n = tmp.length;
        Deque<Integer> stack = new ArrayDeque<>();
        int res = 0;
        for (int i = 0; i < n; i++) {
            while(!stack.isEmpty() && tmp[i] < tmp[stack.peek()]) {
                int h = tmp[stack.pop()];
                res = Math.max(res, (i - stack.peek() -1) * h);
            }
            stack.push(i);
        }
        return res;
    }
}    

参考

标签:tmp,柱子,int,栈顶,当前,stack,单调
来源: https://www.cnblogs.com/zccfrancis/p/15965122.html