首页 > 编程语言 > 详细

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

时间:2020-04-19 20:44:42      阅读:109      评论:0      收藏:0      [点我收藏+]

题目:给定 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

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

原文:https://www.cnblogs.com/zhuozige/p/12733039.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!