From 71463bc8e048249b802285ac2346581d119f9432 Mon Sep 17 00:00:00 2001 From: lucifer Date: Sat, 4 Apr 2020 13:52:40 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9B=B4=E5=8A=A0=E4=BC=98=E9=9B=85?= =?UTF-8?q?=E7=9A=84Python=20Code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/42.trapping-rain-water.md | 32 ++++++++++-------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/problems/42.trapping-rain-water.md b/problems/42.trapping-rain-water.md index 00bb73b8c..baaedce0e 100644 --- a/problems/42.trapping-rain-water.md +++ b/problems/42.trapping-rain-water.md @@ -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 ```