-
Notifications
You must be signed in to change notification settings - Fork 0
/
42.接雨水.py
49 lines (46 loc) · 1.29 KB
/
42.接雨水.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#
# @lc app=leetcode.cn id=42 lang=python3
#
# [42] 接雨水
#
# https://leetcode-cn.com/problems/trapping-rain-water/description/
#
# algorithms
# Hard (44.39%)
# Likes: 453
# Dislikes: 0
# Total Accepted: 17.2K
# Total Submissions: 38.6K
# Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
#
# 给定 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
#
#
from typing import List
# 完全想不到的解答。。。
class Solution:
def trap(self, height: List[int]) -> int:
if not height or len(height) < 3:
return 0
volume = 0
left, right = 0, len(height) - 1
l_max, r_max = height[left], height[right]
while left < right:
l_max, r_max = max(height[left], l_max), max(height[right], r_max)
if l_max <= r_max:
volume += l_max - height[left]
left += 1
else:
volume += r_max - height[right]
right -= 1
return volume