给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
示例 2:
输入:height = [4,2,0,3,2,5]
输出:9
提示:
题目链接
时间复杂度:O(n),其中 n 为 height 的长度。
空间复杂度:O(n)。
class Solution:
def trap(self, height: List[int]) -> int:
# 前缀和数组,其中第0个是原数组的第0个
front = [0]*len(height)
front[0] = height[0]
# 后缀和数组,其中第-1个是原数组的第-1个
back = [0]*len(height)
back[-1] = height[-1]
res = 0
for i in range(1,len(height)):
front[i] = max(front[i-1],height[i])
for j in range(len(height)-2,-1,-1):
back[j] = max(back[j+1],height[j])
for h,f,b in zip(height,front,back):
res+=min(f,b)-h
return res
用两个变量记录前缀最大值和后缀最大值,一边移动指针一边更新最大值
时间复杂度:O(n),其中 n 为 height 的长度。
空间复杂度:O(1)。
如果在外面给 lmax 和 rmax 赋值,那么循环里就在后面更新lmax 和rmax
class Solution:
def trap(self, height: List[int]) -> int:
lmax = height[0]
rmax = height[-1]
res = 0
l = 0
r =len(height)-1
while l<r:
if lmax < rmax:
res+= lmax - height[l]
l+=1
else:
res+=rmax-height[r]
r-=1
lmax = max(lmax,height[l])
rmax = max(rmax,height[r])
return res
如果不在外面赋值,就在最开始就更新lmax 和rmax
class Solution:
def trap(self, height: List[int]) -> int:
lmax = 0
rmax = 0
res = 0
l = 0
r =len(height)-1
while l<r:
lmax = max(lmax,height[l])
rmax = max(rmax,height[r])
if lmax < rmax:
res += lmax - height[l]
l+=1
else:
res += rmax - height[r]
r-=1
return res