Update 0042接雨水.md 动态规划和单调栈Python3 版本

This commit is contained in:
lichun-chen
2021-08-13 21:42:03 -05:00
committed by GitHub
parent 70524a1521
commit 52cf4e0f18

View File

@ -388,6 +388,44 @@ class Solution:
res += res1
return res
```
动态规划
```python3
class Solution:
def trap(self, height: List[int]) -> int:
leftheight, rightheight = [0]*len(height), [0]*len(height)
leftheight[0]=height[0]
for i in range(1,len(height)):
leftheight[i]=max(leftheight[i-1],height[i])
rightheight[-1]=height[-1]
for i in range(len(height)-2,-1,-1):
rightheight[i]=max(rightheight[i+1],height[i])
result = 0
for i in range(0,len(height)):
summ = min(leftheight[i],rightheight[i])-height[i]
result += summ
return result
```
单调栈
```python3
class Solution:
def trap(self, height: List[int]) -> int:
st =[0]
result = 0
for i in range(1,len(height)):
while st!=[] and height[i]>height[st[-1]]:
midh = height[st[-1]]
st.pop()
if st!=[]:
hright = height[i]
hleft = height[st[-1]]
h = min(hright,hleft)-midh
w = i-st[-1]-1
result+=h*w
st.append(i)
return result
```
Go: