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

发布时间 2023-10-11 05:35:42作者: Johnson_强生仔仔

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里面

 

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

考虑以下模板,因为是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题目有:

    [LeetCode] 975. Odd Even Jump_Hard tag: stack, dynamic programming

    [LeetCode] 2334. Subarray With Elements Greater Than Varying Threshold_Hard tag: dp, stack

 

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

以下有待整理