zoukankan      html  css  js  c++  java
  • 刷题笔记——单调栈

    保持栈的单调,只有栈为空或比栈顶大/小的元素才可入栈,否则出栈直到满足条件

    In order to keep the stack monotonic, only when the stack is empty or the top element of the stack is smaller/bigger than the input one, the element will  be pushed into the stack. Otherwise, pop the elements from the stack until the criteria meets.

    For an example:

    lettcode 84

    在这个问题中,应用了单调栈的思想,只有比栈顶大的元素才可入栈

    出栈时,对出栈元素的左右边界进行计算,栈顶的左边界为0,其他元素左右边界均为栈中相邻元素的数组下标,出栈元素的值*边界长度为待求子矩形的面积

    class Solution:
        def largestRectangleArea(self, heights: [int]) -> int:
            if len(heights) == 0:return 0
            max_stack = []
            maxs = heights[0]
            for i in range(len(heights)):
                if len(max_stack) == 0 or max_stack[-1][0] <= heights[i]:
                    max_stack.append([heights[i], i])
                else:
                    top = max_stack[-1][1]
                    while len(max_stack) > 0 and max_stack[-1][0] > heights[i]:
                        last = max_stack.pop()
                        if len(max_stack) > 0:
                            maxs = max(maxs, last[0] * (top - max_stack[-1][1]))
                        else:
                            maxs = max(maxs, last[0] * (top + 1))
                    max_stack.append([heights[i], i])
    
            top = max_stack[-1][1]
            while len(max_stack) > 0:
                last = max_stack.pop()
                if len(max_stack) > 0:
                    maxs = max(maxs, last[0] * (top - max_stack[-1][1]))
                else:
                    maxs = max(maxs, last[0] * (top + 1))
    
            return maxs
  • 相关阅读:
    有nativeQuery = true和没有的区别
    itext隐藏table的单元格边框
    Semaphore (参考资料,还没细看)
    STL 一级/二级空间配置器
    内联函数
    死锁
    用户态和内核态
    关于变量的可见性和生命周期
    主从库原理
    xx亿数据处理
  • 原文地址:https://www.cnblogs.com/yuelien/p/13929811.html
Copyright © 2011-2022 走看看