Skip to content

Commit 241af0a

Browse files
committed
Update leetcode 42
1 parent 4be887d commit 241af0a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

leetcode/42.trapping-rain-water.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,31 @@
3232

3333

3434
class Solution:
35+
# two pointer solution
36+
# https://leetcode.com/problems/trapping-rain-water/solution/
3537
def trap(self, height: List[int]) -> int:
38+
length = len(height)
39+
# forward
40+
lmax = rmax = 0
41+
lp = 0
42+
rp = length - 1
43+
result = 0
44+
while lp < rp:
45+
if height[lp] < height[rp]:
46+
if height[lp] > lmax:
47+
lmax = height[lp]
48+
else:
49+
result += lmax - height[lp]
50+
lp += 1
51+
else:
52+
if height[rp] > rmax:
53+
rmax = height[rp]
54+
else:
55+
result += rmax - height[rp]
56+
rp -= 1
57+
return result
58+
59+
def trap2(self, height: List[int]) -> int:
3660
length = len(height)
3761
# forward
3862
last = 0

0 commit comments

Comments
 (0)