第八周第二次作业

选题:

42Trapping 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设为下一个阶段开始的高度,循环往复。


代码展示:

    

def trap( self, height):
"""
:type height: List[int]
:rtype: int
"""

total = 0 #总的储水量
total_tmp = 0 #每一个阶段的储水量
current = 0 #当前最大高度对应的索引号
index = 0 #height索引
secondheight = 0 #一个阶段中第二高对应的索引号
total_tosh = 0 #从current到secondheight的水量

while index < len (height):

if height [index ] >= height [current ] :
""" 找到一个不低于height[current]的时候,将该阶段的水量进行结算 """
total += total_tmp
total_tmp = 0
total_tosh = 0
current = index
if index == ( len (height) - 1):
return total
else:
secondheight = current + 1
index += 1
continue

elif (index + 1 ) >= len (height):
""" 当发现直到结束都没有找到不低于height[current]的时候,
将从current到secondheight的水量作为一个阶段来结算
"""
if height [secondheight ] <= height [index ]:
#将如果height[secondheight] <= height[index]
#更换secondheight为当前index
#同时计算目前阶段的水量
secondheight = index
total_tmp += height [current ] - height [index ]
total_tosh = total_tmp

#将从current到secondheight的水量加入到总水量中
total = total + total_tosh - (secondheight - current ) * (height [current ] - height [secondheight ])
#将secondheight作为current,进入下一阶段
current = secondheight

if secondheight < ( len (height) - 1):
#如果secondheight不是列表最后一个索引的时候
#进行重置
secondheight += 1
index = secondheight
total_tosh = 0
total_tmp = 0
continue
else:
#如果secondheight是列表最后一个索引的时候,直接返回结果
return total
else:
#计算该阶段的水量
total_tmp += height [current ] - height [index ]


#更新secondheight
if height [secondheight ] <= height [index ]:
secondheight = index
total_tosh = total_tmp

index += 1

return total

    结果展示:



猜你喜欢

转载自blog.csdn.net/shi_gu_re/article/details/80114602