原题地址:https://oj.leetcode.com/problems/trapping-rain-water/

给一个数组[0,1,0,2,1,0,1,3,2,1,2,1],用直方图表示,向里面灌水,问能灌多少水。
刚开始我的思路就有问题,我计算的是每两个相邻凹槽能灌的水的总量结果错了。
修正后的思路是这样的(参考了网上文章),找出最长的一条,index为i,从0到i之间计算。然后再从右往左,从结尾到i,通过这种方式,我们只需要考虑单方向,简化了问题。代码如下
class Solution:
# @param A, a list of integers
# @return an integer
def trap(self, A):
if len(A) <= 2:
return 0
maxIndex = 0
for i in range(0,len(A)):
if A[maxIndex]<A[i]:
maxIndex = i
currentMax = A[0]
sum = 0
for i in range(0,maxIndex+1):
if currentMax >= A[i]:
sum += (currentMax - A[i])
else:
currentMax = A[i]
currentMax = A[len(A)-1]
for i in range(maxIndex,len(A))[::-1]:
if currentMax >= A[i]:
sum += (currentMax - A[i])
else:
currentMax = A[i]
return sum
本文介绍了一种解决直方图灌水问题的优化算法,通过找到最长一条并分段计算,简化了问题求解过程,提高了算法效率。
366

被折叠的 条评论
为什么被折叠?



