From 7ee790f4f532e56664642163a4612c7242f0fe11 Mon Sep 17 00:00:00 2001 From: ccchooko <648646891@qq.com> Date: Fri, 10 Jun 2022 22:34:11 +0800 Subject: [PATCH] =?UTF-8?q?0042=20=E6=8E=A5=E9=9B=A8=E6=B0=B4=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E5=8D=95=E8=B0=83=E6=A0=88go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0042.接雨水.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index b232ce22..e331967f 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -640,8 +640,44 @@ func min(a,b int)int{ } ``` +单调栈解法 +```go +func trap(height []int) int { + if len(height) <= 2 { + return 0 + } + st := make([]int, 1, len(height)) // 切片模拟单调栈,st存储的是高度数组下标 + var res int + for i := 1; i < len(height); i++ { + if height[i] < height[st[len(st)-1]] { + st = append(st, i) + } else if height[i] == height[st[len(st)-1]] { + st = st[:len(st)-1] // 比较的新元素和栈顶的元素相等,去掉栈中的,入栈新元素下标 + st = append(st, i) + } else { + for len(st) != 0 && height[i] > height[st[len(st)-1]] { + top := st[len(st)-1] + st = st[:len(st)-1] + if len(st) != 0 { + tmp := (min(height[i], height[st[len(st)-1]]) - height[top]) * (i - st[len(st)-1] - 1) + res += tmp + } + } + st = append(st, i) + } + } + return res +} +func min(x, y int) int { + if x >= y { + return y + } + return x +} +``` + ### JavaScript: ```javascript