代码改变世界

Data structure - Stack 小结及leetcode相关题目

  Johnson_强生仔仔  阅读(17)  评论(0编辑  收藏  举报

Linear data structure

- Stack    

  • O(1) for push
  • O(1) for pop
  • O(1) for top

 

- Basic skills

先进后出

 

得到 [0, i] 目前为止subarray nums[:i + 1]的最小值/代表物(TreeNode),每次将num[i] 和目前的最小值组成tuple放到stack里面

 

strict increasing stack

1) 得到nearest 第一个左边比nums[i]小的,nearest第一个右边比该点小的 

2) 当前的index 之前不会有比nums[index] 大的。

考虑以下模板,因为是increase,如果需要强行将所有的num pop,需要将0 或者最小值放进nums

length, 如果不考虑exclusive 比nums[i]小的index,length = right_index - stack[-1] - 1 if stack else right_index

 

复制代码
        heights.append(0)
        stack = [] # strict increase stack
        ans = 0
        for index, num in enumerate(heights):
            while stack and heights[stack[-1]] >= num:
                pop_index = stack.pop()
                length = index - stack[-1] - 1 if stack else index
                ans = max(ans, heights[pop_index] * length)
            stack.append(index)
        return ans
复制代码

适用于模板的leetcode题目有:

- 得到nearest 第一个左边比nums[i]大的,nearest第一个右边比该点大的  => strict decreasing stack

以下有待整理

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示