算法分析课每周练习 Trapping Rain Water
2017-07-05 22:37
381 查看
题目
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.
分析
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
leftmosthigh = [0 for i in range(len(height))]
leftmax = 0
for i in range(len(height)):
if height[i] > leftmax: leftmax = height[i]
leftmosthigh[i] = leftmax
sum = 0
rightmax = 0
for i in reversed(range(len(height))):
if height[i] > rightmax: rightmax = height[i]
if min(rightmax, leftmosthigh[i]) > height[i]:
sum += min(rightmax, leftmosthigh[i]) - height[i]
return sum这就是我室友面试时遇到的题
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.
分析
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
leftmosthigh = [0 for i in range(len(height))]
leftmax = 0
for i in range(len(height)):
if height[i] > leftmax: leftmax = height[i]
leftmosthigh[i] = leftmax
sum = 0
rightmax = 0
for i in reversed(range(len(height))):
if height[i] > rightmax: rightmax = height[i]
if min(rightmax, leftmosthigh[i]) > height[i]:
sum += min(rightmax, leftmosthigh[i]) - height[i]
return sum这就是我室友面试时遇到的题
相关文章推荐
- 算法分析课每周练习 Sliding Window Maximum
- 算法分析课每周练习 Find Median from Data Stream
- 算法分析课每周练习 Median of Two Sorted Arrays
- 算法分析课每周练习 Minimum Window Substring
- 算法分析课每周练习 First Missing Positive
- 算法分析课每周练习 LRU Cache
- 算法分析课每周练习 Merge k Sorted Lists
- 算法分析课每周练习 Regular Expression Matching
- 算法分析课每周练习 The Skyline Problem
- 算法分析课每周练习 Serialize and Deserialize Binary Tree
- 算法分析课每周练习 Wildcard Matching
- 算法分析课每周练习 Count of Smaller Numbers After Self
- 算法分析课每周练习 Binary Tree Maximum Path Sum
- 算法分析课每周练习 Longest Increasing Path in a Matrix
- 算法分析课每周练习 Max Points on a Line
- 算法分析课每周练习 Word Search II
- 每周算法练习——动态规划
- [SHA-1算法练习] sha1crackme算法分析
- 每周算法练习——大数的乘法问题
- ACM算法-时间复杂度分析(6.相关练习exercise)