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.
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 the Rain Water (blue section) is being trapped.
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]output:6
This topic is similar to the barrel principle, the middle can collect the water, depending on the left and right sides of the shorter height, and then go to the middle, until the two meet. So set L, R, LH (left height), rh (right height), Judge L,r point to building
That short move which, for example L refers to the shorter, then l+= 1, then if the new building than the corresponding left height to short, ans + = left height-building[l], otherwise height = building[l], if R refers to a shorter, then
The situation is similar.
1. Constraints
1) empty, Edge case, return 0
2) element would be >= 0 integer
2. Ideas
Points: t:o (n) s:o (1)
3. Code
classSolution:defTraprainwater (self, heights):if notHeightsreturn0 L, R, ans= 0, Len (Heights)-1, 0 LH, RH=Heights[l], Heights[r] whileL <r:ifHEIGHTS[L] <=Heights[r]: l+ = 1ifHEIGHTS[L] <Lh:ans+ = LH-Heights[l]Else: LH=Heights[l]Else: R-= 1ifHEIGHTS[R] <Rh:ans+ = RH-Heights[r]Else: RH=Heights[r]returnAns
4. Test Cases
1) Empty
2) 1, 2, 3
3)
[0,1,0,2,1,0,1,3]
[Leetcode] 42. Trapping Rain Water_hard tag:two pointers