Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 617104a

Browse files
committed
add 42
1 parent f80b627 commit 617104a

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
# 0042.trapping-rain-
3+
4+
```text
5+
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
6+
7+
8+
9+
示例 1:
10+
11+
12+
13+
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
14+
输出:6
15+
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
16+
示例 2:
17+
18+
输入:height = [4,2,0,3,2,5]
19+
输出:9
20+
21+
22+
提示:
23+
24+
n == height.length
25+
0 <= n <= 3 * 104
26+
0 <= height[i] <= 105
27+
28+
来源:力扣(LeetCode)
29+
链接:https://leetcode-cn.com/problems/trapping-rain-water
30+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
31+
```
32+
33+
34+
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package water
2+
3+
import "fmt"
4+
5+
func Run() {
6+
height := []int{4, 2, 0, 3, 2, 5}
7+
t := trap(height)
8+
fmt.Println(t)
9+
}
10+
11+
func trap(height []int) int {
12+
t := 0
13+
size := len(height)
14+
for i := 1; i < size-1; i++ {
15+
maxL, maxR := 0, 0
16+
for j := i; j >= 0; j-- {
17+
maxL = max(maxL, height[j])
18+
}
19+
for j := i; j < size; j++ {
20+
maxR = max(maxR, height[j])
21+
}
22+
t += min(maxL, maxR) - height[i]
23+
}
24+
return t
25+
}
26+
27+
func max(i, j int) int {
28+
if i > j {
29+
return i
30+
}
31+
return j
32+
}
33+
34+
func min(i, j int) int {
35+
if i > j {
36+
return j
37+
}
38+
return i
39+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
package water
3+
4+
import "testing"
5+
6+
func TestRun(t *testing.T) {
7+
Run()
8+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /