盛最多水的容器 接雨水【基础算法精讲 03】_哔哩哔哩_bilibili
11. 盛最多水的容器
class Solution:
def maxArea(self, height: List[int]) -> int:
v=0
i=0
j=len(height)-1
while i<j:
h1=height[i]
h2=height[j]
h=min(h1,h2)
v=max(v,h*(j-i))
if h==height[i]:
i+=1
else:
j-=1
return v
42. 接雨水
前后缀分解
class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)
pre_max = [0] * n
pre_max[0] = height[0]
for i in range(1, n):
pre_max[i] = max(pre_max[i - 1], height[i])
suf_max = [0] * n
suf_max[-1] = height[-1]
for i in range(n - 2, -1, -1):
suf_max[i] = max(suf_max[i + 1], height[i])
ans = 0
for h, pre, suf in zip(height, pre_max, suf_max):
ans += min(pre, suf) - h
return ans
相向双指针
class Solution:
def trap(self, height: List[int]) -> int:
ans = left = pre_max = suf_max = 0
right = len(height) - 1
while left <= right:
pre_max = max(pre_max, height[left])
suf_max = max(suf_max, height[right])
if pre_max < suf_max:
ans += pre_max - height[left]
left += 1
else:
ans += suf_max - height[right]
right -= 1
return ans