Skip to content

Commit c4b35e2

Browse files
committed
feat: trapping rain water
gp
1 parent 1cb75ea commit c4b35e2

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

Diff for: stack.trapping-rain-water.py

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
42. 接雨水
6+
https://leetcode-cn.com/problems/trapping-rain-water/
7+
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
8+
"""
9+
# 双指针
10+
def trap(self, height: List[int]) -> int:
11+
res = 0
12+
n = len(height)
13+
if n == 0:
14+
return res
15+
16+
l_max = height[0]
17+
r_max = height[n - 1]
18+
# 定义左指针
19+
l = 0
20+
# 定义右指针
21+
r = n - 1
22+
23+
while l <= r:
24+
# 获取左边最大值
25+
l_max = max(l_max, height[l])
26+
# 获取右边最大值
27+
r_max = max(r_max, height[r])
28+
29+
# 当左边最大值小于右边最大值,则最多盛水 l_max - height[i]
30+
if l_max < r_max:
31+
res += l_max - height[l]
32+
l += 1
33+
else:
34+
res += r_max - height[r]
35+
r -= 1
36+
37+
return res
38+
39+
# 备忘录方式:计算并缓存住每个位置左右两侧的最大高度
40+
def trapByNote(self, height: List[int]) -> int:
41+
res = 0
42+
if not height:
43+
return res
44+
length = len(height)
45+
l_max = [0] * length
46+
r_max = [0] * length
47+
l_max[0] = height[0]
48+
r_max[length - 1] = height[length - 1]
49+
50+
# 从左向右计算 l_max
51+
for i in range(1, length):
52+
l_max[i] = max(height[i], l_max[i-1])
53+
54+
# 从右向左计算 r_max
55+
for i in range(length-2, 0, -1):
56+
r_max[i] = max(height[i], r_max[i+1])
57+
58+
# 计算每个高度
59+
for i in range(1, length - 1):
60+
res += min(l_max[i], r_max[i]) - height[i]
61+
62+
return res
63+
64+
# 暴力破解:获取每根柱子可以盛放的水
65+
def trapByForce(self, height: List[int]) -> int:
66+
length = len(height)
67+
res = 0
68+
for i in range(1, length - 1):
69+
l_max = 0
70+
r_max = 0
71+
# 获取右侧的最大高度
72+
for j in range(i, length):
73+
r_max = max(r_max, height[j])
74+
75+
# 获取左侧的最大高度
76+
for k in range(0, i):
77+
l_max = max(l_max, height[k])
78+
79+
# 相对较小的高度减去当前柱子的高度,就是当前柱子可盛放的高度
80+
tmp_res = min(l_max, r_max) - height[i]
81+
res += tmp_res if tmp_res >= 0 else 0
82+
83+
return res
84+
85+
86+
so = Solution()
87+
# result is 9
88+
print(so.trap([0,1,0,2,1,0,1,3,2,1,2,1]))

0 commit comments

Comments
 (0)