一.题目:
给一个数组,里面都是非负数,求它们困住的水的最大体积是多少?
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
二.解题思路:
确定一个位置所能存住的水的体积是由其两边的较短的那根柱子决定的.所以我们首先确定两个变量left_max,right_max,并在遍历数组时更新它们的值.
代码如下:
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left = 0
right = len(height) - 1
left_max = right_max = water = 0
#left_max 表示左边的最大值,right_max表示右边的最大值
while left <= right:
if left_max <= right_max:
left_max = max(left_max, height[left])
water += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
water += right_max - height[right]
right -= 1
return water
本文详细解析了如何通过双指针法求解数组困水问题,即在一个由非负数构成的数组中,找到能困住的最大水量。文章提供了一个Python实现的示例代码,通过维护左右最大值来高效地解决此问题。
400

被折叠的 条评论
为什么被折叠?



