Source of the topic:
https://leetcode.com/problems/trapping-rain-water/
Test Instructions Analysis:
Enter a set of arrays representing a height map with a width of 1. Q, how much water can this map collect after the rain? For example, enter an array [0,1,0,2,1,0,1,3,2,1,2,1] and return 6.:
Topic Ideas:
Although this topic is hard difficulty, but it is not very difficult. It is not difficult to find that the water is from the highest number and the second high number. So this question can be divided into two parts. ① finds the maximum value of the array. ② calculates the maximum amount of water that can be collected on the left and right respectively; To calculate the left side, first find the left-most left-hand height, calculate the water collected between it and the highest number and the second high-to-left and the formal representation is f (i) = W (i,j) + f (j), F (i) represents the water collected from I to the left, W (i, j) Represents the water collected between I and J. W (i,j) and easy to calculate, which is the sum of the second high minus the original height between I and J; The complexity of Time is (O (n)).
Code (Python):
1 classsolution (object):2 defLeft (self,height,i):3 ifi = =0:4 return05n = i-1;mi = N;maxh =Height[mi]6 whileN >=0:7 ifHeight[n] >=Maxh:8Maxh = Height[n];mi =N9N-= 1TenAns = 0;k =mi One whileK <I: AAns + = maxh-Height[k] -K + = 1 - returnAns +self.left (HEIGHT,MI) the defRight (self,height,i): -Size =len (height) - ifi = = Size-1: - return0 +n = i + 1; mi = N;maxh =Height[mi] - whileN <Size: + ifHeight[n] >=Maxh: AMaxh = Height[n];mi =N atn + = 1 -Ans = 0;k =mi - whileK >I: -Ans + = maxh-height[k];k-=1 - returnAns +self.right (HEIGHT,MI) - defTrap (self, height): in """ - : Type Height:list[int] to : Rtype:int + """ -s =len (height) the ifs = =0: * return0 $MH = height[0];m = 0; i = 1Panax Notoginseng whileI <S: - ifHeight[i] >=MH: theMH = Height[i];m =I +i + = 1 A returnSelf.left (height,m) +self.right (height,m) the
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/4934365.html
[Leetcode] (python): 042-trapping Rain Water