Skip to content

Commit

Permalink
Merge pull request youngyangyang04#892 from baici1/master
Browse files Browse the repository at this point in the history
增加42接雨水 go版本的动态规划解法
  • Loading branch information
youngyangyang04 authored Nov 14, 2021
2 parents 7c9109d + fe2362a commit bcbb8b9
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions problems/0042.接雨水.md
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,48 @@ func trap(height []int) int {
}
```

动态规划解法:

```go
func trap(height []int) int {
sum:=0
n:=len(height)
lh:=make([]int,n)
rh:=make([]int,n)
lh[0]=height[0]
rh[n-1]=height[n-1]
for i:=1;i<n;i++{
lh[i]=max(lh[i-1],height[i])
}
for i:=n-2;i>=0;i--{
rh[i]=max(rh[i+1],height[i])
}
for i:=1;i<n-1;i++{
h:=min(rh[i],lh[i])-height[i]
if h>0{
sum+=h
}
}
return sum
}
func max(a,b int)int{
if a>b{
return a
}
return b
}
func min(a,b int)int{
if a<b{
return a
}
return b
}
```



JavaScript:

```javascript
//双指针
var trap = function(height) {
Expand Down

0 comments on commit bcbb8b9

Please sign in to comment.