classSolution: deftrap(self, height: List[int]) -> int: # 边界条件 ifnot height: return0 n = len(height) maxleft = [0] * n maxright = [0] * n ans = 0 # 初始化 maxleft[0] = height[0] maxright[n-1] = height[n-1] # 设置备忘录,分别存储左边和右边最高的柱子高度 for i inrange(1,n): maxleft[i] = max(height[i],maxleft[i-1]) for j inrange(n-2,-1,-1): maxright[j] = max(height[j],maxright[j+1]) # 一趟遍历,比较每个位置可以存储多少水 for i inrange(n): ifmin(maxleft[i],maxright[i]) > height[i]: ans += min(maxleft[i],maxright[i]) - height[i] return ans
太妙了,就只计算我头顶有多少水,最后加起来就行了,简洁明了。
Donate
Copyright:
Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.