简单解法
从列表左边开始搜索,定义left=0,如果右边的数小于左边,则固定左边向右搜索,直到遇到右边某个数大于左边的数,或大于左边后的一个数,否则left+1
class Solution:
def trap(self, height):
output = 0
left = 0
while left<len(height)-1:
right = left+1
if height[right]>=height[left]:
left+=1
continue
else:
r = right
s = height[right]
while right<len(height)-1 and height[right]<height[left]:
right +=1
if height[right]>s:
s = height[right]
r = right
if height[right]< height[left] and r==left+1:
left = r
continue
elif height[right]< height[left]:
right = r
line = min(height[left],height[right])
for i in range(left+1,right):
output += line - height[i]
left =right
return output
遍历算法
构造两个列表,左向列表和右向列表,分别代表从左/右遍历,每个位置之前出现过的最大数,再用相同位置的两个列表的数的最小值,减去当前位置的数,便可以得到当前位置的水的数量。
class Solution:
def trap(self, height):
arr, left, right, water = [], 0, 0, 0
for i in height:
left = max(left, i)
arr.append(left)
arr.reverse()
for n, i in enumerate(reversed(height)):
right = max(right, i)
water += min(arr[n], right) - i
return water
快速算法
定义left和right分别记录左边和右边两边同时遍历出现过的最大的数,左边遍历时,若右边最大的数大于等于左边,同时遍历位置的数字小于左边,则表示该位置有水,右边同理。
class Solution:
def trap(self, height):
left = right = water = 0
i, j = 0, len(height)-1
while i <= j:
left, right = max(left, height[i]), max(right, height[j])
while i <= j and height[i] <= left <= right:
water += left - height[i]
i += 1
while i <= j and height[j] <= right <= left:
water += right - height[j]
j -= 1
return water