选题:
42. Trapping Rain Water
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!
算法思路:
分阶段去计算计算水量,具体多少个阶段要看给出的列表。每一阶段都从一个极大值开始,设为current, 然后去寻找下一个比current大的值,同时记录寻找过程中第二高的值,设为secondheight,每一阶段的水量为 total_tmp += height[current] + height[index],当找到另一个height[index] >= height[current]的时候,将该阶段的水量total_tmp加入到总水量中,然后将当前index设为current,开始下一阶段的计算,直到结束。
难点:当height[current]为列表中最高的那个,该如何计算。
解决方法: 这时需要用到上面说到的secondheight。如果发现直到最后都找不到比height[current]高的值,则将total_tmp设为curent到secondheight的水量,然后将secondheight设为下一个阶段开始的高度,循环往复。
代码展示:
结果展示: