给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:在这里提出每一行每点比较周围点大小的方式,能实现基本功能但不能通过时间判断,在这里先记录该思路代码。
class Solution:
def trap(self, height: List[int]) -> int:
sumnum=0
maxnum=self.Findmax(height)
for no in range(0,maxnum+1):
isStart = False
temp_sum = 0
for position in range(0,len(height)):
if (isStart and height[position] < no):
temp_sum+=1
if (height[position] >= no) :
sumnum = sumnum + temp_sum
temp_sum = 0
isStart = True
return sumnum
def Findmax(self,height):
maxnum=0
for no in height:
if (no>maxnum):
maxnum=no
return maxnum
思路2:使用双指针。
只要 \text{right\_max}[i]>\text{left\_max}[i]right_max[i]>left_max[i] (元素 0 到元素 6),积水高度将由 left_max 决定,类似地 \text{left\_max}[i]>\text{right\_max}[i]left_max[i]>right_max[i](元素 8 到元素 11)。
所以我们可以认为如果一端有更高的条形块(例如右端),积水的高度依赖于当前方向的高度(从左到右)。当我们发现另一侧(右侧)的条形块高度不是最高的,我们则开始从相反的方向遍历(从右到左)。
我们必须在遍历时维护 \text{left\_max}left_max 和 \text{right\_max}right_max ,但是我们现在可以使用两个指针交替进行,实现 1 次遍历即可完成。
作者:LeetCode
链接:https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)-1
left=0
right=n
#left[i]表示i左边的最大值,right[i]表示i右边的最大值
leftMax=0
rightMax=0
water = 0
while(left<right):
if(height[left]<height[right]):
if(height[left]<leftMax):
water+=leftMax-height[left]
else:
leftMax=height[left]
left+=1
else:
if(height[right]<rightMax):
water+=rightMax-height[right]
else:
rightMax=height[right]
right-=1
return water