mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Update 0042接雨水.md 动态规划和单调栈Python3 版本
This commit is contained in:
@ -388,6 +388,44 @@ class Solution:
|
|||||||
res += res1
|
res += res1
|
||||||
return res
|
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:
|
Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user