惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
U
Unit 42
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
Vercel News
Vercel News
美团技术团队
雷峰网
雷峰网
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
D
DataBreaches.Net
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
罗磊的独立博客
MyScale Blog
MyScale Blog
博客园_首页
IT之家
IT之家
F
Fortinet All Blogs
博客园 - Franky

博客园 - Dabay

[Leetcode][Python]56: Merge Intervals [Leetcode][Python]55: Jump Game [Leetcode][Python]54: Spiral Matrix [Leetcode][Python]53: Maximum Subarray [Leetcode][Python]52: N-Queens II [Leetcode][Python]51: N-Queens [Leetcode][Python]50: Pow(x, n) [Leetcode][Python]49: Anagrams [Leetcode][Python]48: Rotate Image [Leetcode][Python]47: Permutations II [Leetcode][Python]46: Permutations [Leetcode][Python]45: Jump Game II [Leetcode][Python]44:Wildcard Matching [Leetcode][Python]43: Multiply Strings [Leetcode][Python]41: First Missing Positive [Leetcode][Python]40: Combination Sum II [Leetcode][Python]39: Combination Sum [Leetcode][Python]19: Remove Nth Node From End of List [Leetcode][Python]37: Sudoku Solver
[Leetcode][Python]42: Trapping Rain Water
Dabay · 2015-03-19 · via 博客园 - Dabay
# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'

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 is 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===
请参考:http://blog.csdn.net/wzy_1988/article/details/17752809
挨个分析每个A[i]能trapped water的容量,然后将所有的A[i]的trapped water容量相加即可
其次,对于每个A[i]能trapped water的容量,取决于A[i]左右两边的高度(可延展)较小值与A[i]的差值,
即volume[i] = [min(left[i], right[i]) - A[i]] * 1,这里的1是宽度,如果the width of each bar is 2,那就要乘以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)