- Trapping Rain Water(python)
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
这个题和11. Container With Most Water是相似的,主要思路是给两个指针,while语句从两边向中间遍历。在遍历时同时求所有的影音面积和数列的和,然后用所有的阴影面积减去数列的和既是乘的水。
def trap(self, height: List[int]) -> int:
i=0
j=len(height)-1
sum1=0
sum2=0
min_num=0
while i<=j:
if height[i]<height[j]:
sum1+=height[i]
if height[i]>min_num:
sum2+=(height[i]-min_num)*(j-i+1)
min_num=height[i]
else:
pass
i+=1
else:
sum1+=height[j]
if height[j]>min_num:
sum2+=(height[j]-min_num)*(j-i+1)
min_num=height[j]
else:
pass
j-=1
return sum2-sum1
代码形式有点罗嗦,不过好在清楚详细,也不影响效率。
本文深入探讨了经典的“雨中蓄水”算法问题,通过双指针技术,计算雨后地形图上能够储存多少雨水。该算法与ContainerWithMostWater相似,采用从两端向中间遍历的方法,计算阴影面积并减去地形高度总和,得到最终蓄水量。
400

被折叠的 条评论
为什么被折叠?



