59 第九章 单调栈
● 503.下一个更大元素II
● 42. 接雨水
class Solution:
def trap(self, height: List[int]) -> int:
# 42. 接雨水
q = collections.deque()
res = height.copy()
preheght_idx = -1
for i in range(len(height)):
# 寻找右边第一个比现在大的值,一直找到最左边,记录左边起始值
b = True
while q and height[i] >= height[q[-1]]:
b = False
preheght_idx = q[-1]
q.pop()
q.append(i)
if b:
continue
# 将这段洼地置为左边填充后水平面的高度
for r in range(preheght_idx, i):
res[r] = max(height[preheght_idx], res[r])
if len(q) >= 2:
for i in range(len(q)-1, 0, -1):
for j in range(q[i-1]+1, q[i]):
res[j] = max(res[j], height[q[i]])
re = 0
for i in range(len(height)):
re += (res[i] - height[i])
return re