[Leetcode] [Python]42:trapping Rain Water

Source: Internet
Author: User

#-*-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.