File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -471,8 +471,50 @@ class Solution:
471471 return dist
472472```
473473
474+ ## 补充:单调栈
475+
476+ 用线性的时间复杂度找左右两侧第一个大于/小于当前元素的位置。
477+
478+ ### [ largest-rectangle-in-histogram] ( https://leetcode-cn.com/problems/largest-rectangle-in-histogram/ )
479+
480+ ``` Python
481+ class Solution :
482+ def largestRectangleArea (self , heights ) -> int :
483+ heights.append(0 )
484+ stack = [- 1 ]
485+ result = 0
486+ for i in range (len (heights)):
487+ while stack and heights[i] < heights[stack[- 1 ]]:
488+ cur = stack.pop()
489+ result = max (result, heights[cur] * (i - stack[- 1 ] - 1 ))
490+ stack.append(i)
491+ return result
492+ ```
493+
494+ ### [ trapping-rain-water] ( https://leetcode-cn.com/problems/trapping-rain-water/ )
495+
496+ ``` Python
497+ class Solution :
498+ def trap (self , height : List[int ]) -> int :
499+
500+ stack = []
501+ result = 0
502+
503+ for i in range (len (height)):
504+ while stack and height[i] > height[stack[- 1 ]]:
505+ cur = stack.pop()
506+ if not stack:
507+ break
508+ result += (min (height[stack[- 1 ]], height[i]) - height[cur]) * (i - stack[- 1 ] - 1 )
509+ stack.append(i)
510+
511+ return result
512+ ```
513+
474514## 补充:单调队列
475515
516+ 单调栈的拓展,可以以线性时间获得区间最大/最小值。
517+
476518### [ sliding-window-maximum] ( https://leetcode-cn.com/problems/sliding-window-maximum/ )
477519
478520> 求滑动窗口中的最大元素
You can’t perform that action at this time.
0 commit comments