Leetcode 42.接雨水 (每日一题 20210629)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 42.接雨水 (每日一题 20210629)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定?n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之后能接多少雨水。示例 1:輸入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
輸出:6
解釋:上面是由數組 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。示例 2:輸入:height = [4,2,0,3,2,5]
輸出:9鏈接:https://leetcode-cn.com/problems/trapping-rain-waterclass Solution:def trap(self, height: List[int]) -> int:if not height:return 0left, right = 0, len(height) - 1max_left, max_right = height[0], height[-1]area = 0while left <= right:max_left = max(max_left, height[left])max_right = max(max_right, height[right])if max_left > max_right:area += max_right - height[right]right -= 1else:area += max_left - height[left]left += 1return area
總結
以上是生活随笔為你收集整理的Leetcode 42.接雨水 (每日一题 20210629)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 199.二叉树的右视图
- 下一篇: Leetcode 6.Z 字形变换 (每