File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -704,6 +704,45 @@ func min(x, y int) int {
704704}
705705```
706706
707+ 单调栈压缩版:
708+
709+ ``` go
710+ func trap (height []int ) int {
711+ stack := make ([]int , 0 )
712+ res := 0
713+
714+ // 无需事先将第一个柱子的坐标入栈,因为它会在该for循环的最后入栈
715+ for i := 0 ; i < len (height); i ++ {
716+ // 满足栈不为空并且当前柱子高度大于栈顶对应的柱子高度的情况时
717+ for len (stack) > 0 && height[stack[len (stack) - 1 ]] < height[i] {
718+ // 获得凹槽高度
719+ mid := height[stack[len (stack) - 1 ]]
720+ // 凹槽坐标出栈
721+ stack = stack[: len (stack) - 1 ]
722+
723+ // 如果栈不为空则此时栈顶元素为左侧柱子坐标
724+ if len (stack) > 0 {
725+ // 求得雨水高度
726+ h := min (height[i], height[stack[len (stack) - 1 ]]) - mid
727+ // 求得雨水宽度
728+ w := i - stack[len (stack) - 1 ] - 1
729+ res += h * w
730+ }
731+ }
732+ // 如果栈为空或者当前柱子高度小于等于栈顶对应的柱子高度时入栈
733+ stack = append (stack, i)
734+ }
735+ return res
736+ }
737+
738+ func min (x , y int ) int {
739+ if x < y {
740+ return x
741+ }
742+ return y
743+ }
744+ ```
745+
707746### JavaScript:
708747
709748``` javascript
You can’t perform that action at this time.
0 commit comments