Stack-----84. Largest Rectangle in Histogram

原题目
参考资料

这种实在是,。,。记得有几种类型的题都是两个指针中间挤,其实这里是一点思路都没有,因为涉及到保留之前的数据,两个指针就不是那么好用了。下面这种解法还是比较新奇的,用一个栈来保留前面递增的索引号,然后从当前索引往前面进行倒推计算。

   public int largestRectangleArea(int[] heights) {
        if (heights == null || heights.length == 0) {
            return 0;
        }
        Stack<Integer> stack = new Stack<>();
        int max = Integer.MIN_VALUE;
        int current = 0;
        for (int i = 0; i <= heights.length; i++) {

            if (i != heights.length - 1) {
                current = -1;
            } else {
                current = heights[i];
            }
            while (!stack.isEmpty() && current <= heights[stack.peek()]) {
                int height = heights[stack.pop()];
                int w = 0;
                //栈为空的条件要注意,这里的stack为空的时候可能是前面历史留下来的
                if (stack.isEmpty()) {
                    w = i;
                } else {
                    w = i - stack.peek() - 1;
                }
                max = Math.max(max, height * w);
            }
            stack.push(i);
        }
        return max;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值