Skip to content

Commit

Permalink
feat: 更加优雅的Python Code
Browse files Browse the repository at this point in the history
  • Loading branch information
azl397985856 committed Apr 4, 2020
1 parent d3543f8 commit 71463bc
Showing 1 changed file with 11 additions and 21 deletions.
32 changes: 11 additions & 21 deletions problems/42.trapping-rain-water.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,26 +96,16 @@ var trap = function(height) {
Python Code:

```python

class Solution:
def trap(self, height: List[int]) -> int:
maxLeft, maxRight, volum = 0, 0, 0
maxLeftStack, maxRightStack = [], []
for h in height:
if h > maxLeft:
maxLeftStack.append(h)
maxLeft = h
else:
maxLeftStack.append(maxLeft)
for h in height[::-1]:
if h > maxRight:
maxRightStack.append(h)
maxRight = h
else:
maxRightStack.append(maxRight)
maxRightStack = maxRightStack[::-1]
for i in range(1, len(height) - 1):
minSide = min(maxLeftStack[i], maxRightStack[i])
volum += minSide - height[i]
return volum
def trap(self, heights: List[int]) -> int:
n = len(heights)
l, r = [0] * (n + 1), [0] * (n + 1)
ans = 0
for i in range(1, len(heights) + 1):
l[i] = max(l[i - 1], heights[i - 1])
for i in range(len(heights) - 1, 0, -1):
r[i] = max(r[i + 1], heights[i])
for i in range(len(heights)):
ans += max(0, min(l[i + 1], r[i]) - heights[i])
return ans
```

0 comments on commit 71463bc

Please sign in to comment.