LeetCode42 接雨水
问题描述
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
思路
思路一:遍历
思路二:双指针
思路三: 动态规划
代码
思路一代码
func trap(height []int) int {
var res int
for i := 0; i < len(height); i++ {
max_left, max_right := 0, 0
for j := i; j >= 0; j-- {
max_left = max(max_left, height[j])
}
for j := i; j < len(height); j++ {
max_right = max(max_right, height[j])
}
res += min(max_left, max_right) - height[i]
}
return res
}
func max(a, b int) int {
if a < b {
a = b
}
return a
}
func min(a, b int) int {
if a > b {
a = b
}
return a
}
思路二代码
func trap(height []int) int {
var res int
left, right := 0, len(height) - 1
left_max, right_max := 0, 0
for left < right {
if height[left] < height[right] {
if height[left] >= left_max {
left_max = height[left]
} else {
res += (left_max - height[left])
}
left++
} else {
if height[right] >= right_max {
right_max = height[right]
} else {
res += (right_max - height[right])
}
right--
}
}
return res
}