2025-07-28 19:09:41 +08:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
|
resule := trap([]int{4, 2, 0, 3, 2, 5})
|
|
|
|
|
|
fmt.Println("最大接水数为:", resule)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func trap(height []int) int {
|
2025-08-08 20:16:08 +08:00
|
|
|
|
leftP := 0
|
|
|
|
|
|
rightP := 1
|
|
|
|
|
|
result := 0
|
|
|
|
|
|
midres := 0
|
|
|
|
|
|
for {
|
|
|
|
|
|
if leftP > len(height)-1 || rightP > len(height)-1 {
|
|
|
|
|
|
break
|
|
|
|
|
|
}
|
|
|
|
|
|
if height[leftP] > height[rightP] {
|
|
|
|
|
|
midres += height[leftP] - height[rightP]
|
2025-08-16 12:45:40 +08:00
|
|
|
|
fmt.Println("result加上:", height[leftP]-height[rightP], "当前1左指针:", leftP, "当前右指针:", rightP)
|
2025-08-08 20:16:08 +08:00
|
|
|
|
rightP++
|
|
|
|
|
|
} else if height[leftP] <= height[rightP] && midres != 0 {
|
|
|
|
|
|
result += midres
|
|
|
|
|
|
leftP = rightP
|
|
|
|
|
|
rightP = leftP + 1
|
|
|
|
|
|
} else {
|
|
|
|
|
|
leftP++
|
|
|
|
|
|
rightP = leftP + 1
|
|
|
|
|
|
}
|
2025-07-28 19:09:41 +08:00
|
|
|
|
}
|
2025-08-08 20:16:08 +08:00
|
|
|
|
return result
|
2025-07-28 19:09:41 +08:00
|
|
|
|
}
|