#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
42:trapping Rain Water
https://oj.leetcode.com/problems/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 was able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
===comments by dabay===
Please refer to: http://blog.csdn.net/wzy_1988/article/details/17752809
Analyze each a[i] to trapped water capacity, then add trapped water capacity of all A[i]
Second, for each a[i] can trapped water capacity, depending on the height of the left and right side of the A[i] (extendable) The difference between the smaller and A[i],
i.e. Volume[i] = [min (Left[i], right[i])-a[i]] * 1, here the 1 is the width, if the width of each bar is 2, it will be multiplied by 2
‘‘‘
Class Solution:
# @param A, a list of integers
# @return An integer
def trap (self, A):
If Len (A) <= 2:
return 0
Highest_on_left = [A[0] for _ in A]
For I in xrange (1, Len (A)):
Highest_on_left[i] = max (highest_on_left[i-1], a[i])
Highest_on_right = [A[-1] for _ in A]
For i in Xrange (Len (A)-2,-1,-1):
Highest_on_right[i] = max (highest_on_right[i+1], a[i])
res = 0
For I in xrange (1, Len (A)-1):
Res + = min (Highest_on_left[i], highest_on_right[i])-a[i]
return res
def main ():
s = solution ()
Nums = [0,1,0,2,1,0,1,3,2,1,2,1]
Print S.trap (nums)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]42:trapping Rain Water