Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d7b97a6

Browse files
author
侯利朋
committed
.\42.接雨水.go ok
1 parent 600a437 commit d7b97a6

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

42.接雨水.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* @lc app=leetcode.cn id=42 lang=golang
3+
*
4+
* [42] 接雨水
5+
*
6+
* https://leetcode-cn.com/problems/trapping-rain-water/description/
7+
*
8+
* algorithms
9+
* Hard (46.21%)
10+
* Likes: 561
11+
* Dislikes: 0
12+
* Total Accepted: 25.4K
13+
* Total Submissions: 55K
14+
* Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
15+
*
16+
* 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
17+
*
18+
*
19+
*
20+
* 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢
21+
* Marcos 贡献此图。
22+
*
23+
* 示例:
24+
*
25+
* 输入: [0,1,0,2,1,0,1,3,2,1,2,1]
26+
* 输出: 6
27+
*
28+
*/
29+
// 4 ms, faster than 88.04%
30+
// 一列一列计算雨水
31+
func trap(height []int) int {
32+
if len(height) == 0 {
33+
return 0
34+
}
35+
// [i]表示前i个元素中的最大值,包含第i个元素
36+
maxLeft := make([]int, len(height))
37+
maxLeft[0] = height[0]
38+
for i :=1; i<len(height);i++ {
39+
if height[i] > maxLeft[i-1] {
40+
maxLeft[i] = height[i]
41+
} else {
42+
maxLeft[i] = maxLeft[i-1]
43+
}
44+
}
45+
// [i] 右边i个元素的最大值,包含第i个元素
46+
maxRight := make([]int, len(height))
47+
maxRight[len(height)-1] = height[len(height)-1]
48+
for i:=len(height)-2; i>=0; i-- {
49+
if height[i] > maxRight[i+1] {
50+
maxRight[i] = height[i]
51+
} else {
52+
maxRight[i] = maxRight[i+1]
53+
}
54+
}
55+
56+
sum := 0
57+
for i:=1; i<len(height)-1; i++ {// 首位不可能有雨水
58+
if height[i] < maxLeft[i-1] && height[i] < maxRight[i+1]{
59+
sum += min(maxLeft[i-1], maxRight[i+1]) - height[i]
60+
}
61+
}
62+
return sum
63+
}
64+
func min(a, b int) int{
65+
if a < b {
66+
return a
67+
}
68+
return b
69+
}
70+

0 commit comments

Comments
 (0)