leetcode 42. 接雨水

题解

首先找出柱子的最大高度maxHeight,然后分别找出从1, 2, 3...maxHeight高度所能接到的雨水,每一次高度所能接到的雨水,就是两个相邻的不低于此高度的柱子之间的距离

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func trap(height []int) int {
maxHeight, res := 0, 0
for _, v := range height {
if maxHeight < v {
maxHeight = v
}
}
for i := 1; i <= maxHeight; i++ {
cur := -1
for j, v := range height {
if cur != -1 && v >= i {
res += j-cur-1
}
if v >= i {
cur = j
}
}
}
return res
}