-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path42.接雨水.go
More file actions
39 lines (36 loc) · 687 Bytes
/
42.接雨水.go
File metadata and controls
39 lines (36 loc) · 687 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
* @lc app=leetcode.cn id=42 lang=golang
*
* [42] 接雨水
*/
package leetcode
// @lc code=start
func trap(height []int) int {
l := len(height)
if l <= 2 {
return 0
}
stack := make([]int, 0)
ret := 0
for i := 0; i < l; i++ {
for len(stack) > 0 && height[i] > height[stack[len(stack)-1]] {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if len(stack) == 0 {
break
}
width := i - stack[len(stack)-1] - 1
boundedHeight := min(height[i], height[stack[len(stack)-1]]) - height[top]
ret += width * boundedHeight
}
stack = append(stack, i)
}
return ret
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// @lc code=end