Leetcode练习(Python):数组类:第42题:给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

题目:给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

 思路:与第11题的思路很像

程序:

class Solution:
    def trap(self, height: List[int]) -> int:
        result = 0
        index_left = 0
        index_right = len(height) - 1
        left_max = 0
        right_max = 0

        while index_left <= index_right:
            if height[index_left] <= height[index_right]:
                if height[index_left] < left_max:
                    result = result + (left_max - height[index_left])
                else:
                    left_max = height[index_left]
                index_left += 1
            else:
                if height[index_right] < right_max:
                    result = result + (right_max - height[index_right])
                else:
                    right_max = height[index_right]
                index_right -= 1
        return result
原文地址:https://www.cnblogs.com/zhuozige/p/12733039.html