classSolution: deftrap(self, height: List[int]) -> int: """木桶效应""" ifnot height: return0 # 求得最高的那一个大柱子的索引 top_column = height.index(max(height)) for i inrange(top_column): if height[i] != 0: del height[:i] break for j inrange(len(height)-1,top_column,-1): if height[j] != 0: del height[j+1:] break # 遍历最高值左边 top_column = height.index(max(height)) total_water = 0 left = 0 # 动态计算最大值 # 遍历最高值左边 for i inrange(1,top_column): # 当前位置的前一个柱子的和其前面的最大值比较 left = max(height[i-1],left) if height[i] < left: total_water += left-height[i] # 遍历最高值右边 right = 0 for i inrange(len(height)-2,top_column,-1): right = max(height[i+1],right) if height[i] < right: total_water += right-height[i] return total_water