数据结构:数组
时间复杂度:O(N)
空间复杂度:O(N)
代码实现:
class Solution:
def trap(self, height: List[int]) -> int:
m = len(height)
to_left = m * [0]
to_right = m * [0]
can_hold = m * [0]
max_height = 0
for i in range(len(height)):
to_left[i] = max_height
max_height = max(max_height, height[i])
max_height = 0
for i in range(m-1, -1, -1):
to_right[i] = max_height
max_height = max(max_height, height[i])
for i in range(len(height)):
hold = min(to_left[i], to_right[i]) - height[i]
if hold > 0:
can_hold[i] = hold
return sum(can_hold)
本文介绍了如何使用Python实现一个名为`trap`的函数,计算给定高度数组中可以容纳水的最大体积。通过双指针法,分别计算左右两侧可以容纳的最大高度,然后找出每个位置能容纳的水的量。该算法的时间复杂度为O(N),空间复杂度也为O(N)。
2177

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



