标签:sum self water 多少 https on() return ems board
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
链接: https://leetcode-cn.com/problems/trapping-rain-water/
如果一个柱子可以作为盛水的边界,那么它一定满足一个条件,要不就是它不小于左边的元素,或者不小于右边的元素,这样它才可能是一个边界。-
class Solution:
def trap(self, height:list) -> int:
if len(height)<=2:
return 0
larger = [0 for i in range(len(height))]
smaller = [0 for i in range(len(height))]
maxh = height[-1]
for i in range(len(height)-1,-1,-1):
if height[i]<maxh:
larger[i] = 1
else:
maxh = height[i]
maxh = height[0]
for i in range(len(height)):
if height[i]<maxh:
smaller[i] = 1
else:
maxh = height[i]
board = [0 for i in range(len(height))]
for i in range(len(height)):
board[i] = 1 if larger[i]+smaller[i]<=1 else 0
area = 0
flag=None
old_flag=None
for i in range(len(board)):
if board[i] == 0:
continue
else:
flag = i
if old_flag is None:
old_flag = flag
continue
area += min(height[flag],height[old_flag])*(flag -old_flag-1) - sum(height[old_flag+1:flag])
old_flag = flag
return area
s = Solution()
print(s.trap([0,0,0])
我思考的时候主要思考的是盛水的边界需要是什么样子的
但是官方题解的大部分思路,在第i个位置,它能够接多少水,也就是找一个位置,两面的边界。这样可以用双指针。
标签:sum self water 多少 https on() return ems board
原文地址:https://www.cnblogs.com/Lzqayx/p/12163339.html