42. Trapping Rain Water
解题思路:
先计算出黑色和蓝色的面积之和,再减去黑色的面积得到就是蓝色的面积即截留水的体积。
黑色和蓝色的面积之和:一层一层地计算
黑色面积:为sum(height)
class Solution:def trap(self, height: List[int]) -> int:if not height:return 0lo, hi = 0, len(height)-1target, boundary = 1, max(height) #计算黑色和蓝色的面积之和,从第一层开始算,最高层为boundary res = 0while lo < hi or target <= boundary:while lo <= hi and height[lo] < target:lo += 1while lo <= hi and height[hi] < target:hi -= 1res += (hi-lo+1) # hi-lo+1为每一层的宽度target += 1return res - sum(height)