Source of the topic
https://leetcode.com/problems/trapping-rain-water/
Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .
Test instructions Analysis
Input:the height of the bars as list
Output:the volumn of the water the bars can save
Conditions: Notice that the bar height is different, so the middle bar can hold a certain amount of water, test instructions is the size of the water to be accommodated
Topic ideas
Note that the amount of water that each bar can hold is the lower value of the bar in its left and right bar, so first create a leftmosthigh list to record the highest bar value before each bar and then traverse backward from the back to the top bar value Calculate the amount of water that each bar can hold at a time
AC Code (PYTHON)
1_author_ ="YE"2 #-*-coding:utf-8-*-3 4 classsolution (object):5 defTrap (self, height):6 """7 : Type Height:list[int]8 : Rtype:int9 """TenL =len (height) OneLeftmosthigh = [0 forIinchRange (len (height))] ALeftmax =0 - forIinchRange (L): -Leftmosthigh[i] =Leftmax the ifHeight[i] >Leftmax: -Leftmax =Height[i] - -Rightmax =0 +sum =0 - forIinchReversed (Range (L)): + ifMin (Rightmax, leftmosthigh[i]) >Height[i]: Asum = sum + min (Rightmax, leftmosthigh[i])-Height[i] at ifHeight[i] >Rightmax: -Rightmax =Height[i] - - returnsum - - inHeight = [0,1,0,2,1,0,1,3,2,1,2,1] -s =solution () to Print(S.trap (height))
[Leetcode] (python): 042-trapping Rain Water