Skip to content

Commit 377d0f8

Browse files
committed
update solution of #42 [faster, shorter, more intuitive]
1 parent 85c8b8f commit 377d0f8

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

python/0042-trapping-rain-water.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,16 @@
11
class Solution:
22
def trap(self, height: List[int]) -> int:
3-
if not height:
4-
return 0
53

6-
l, r = 0, len(height) - 1
7-
leftMax, rightMax = height[l], height[r]
8-
res = 0
9-
while l < r:
10-
if leftMax < rightMax:
11-
l += 1
12-
leftMax = max(leftMax, height[l])
13-
res += leftMax - height[l]
14-
else:
15-
r -= 1
16-
rightMax = max(rightMax, height[r])
17-
res += rightMax - height[r]
18-
return res
4+
c = height.index(max(height))
5+
6+
vol = 0
7+
for arr in [height[:c], height[:c:-1]]:
8+
first = 0
9+
for i in arr:
10+
if i < first:
11+
vol += first - i
12+
else:
13+
first = i
14+
15+
return vol
16+

0 commit comments

Comments
 (0)