简繁EN

LeetCodeNo. 104

【LeetCode with Python】 42. Trapping Rain Water

目錄

題目

原題頁面:https://leetcode.com/problems/trapping-rain-water/
題目型別:Array, Stack, Two Pointers
難度評價:Hard
類似題目:(M) Container With Most Water, (M) Product of Array Except Self

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

rainwatertrap

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. **Thanks Marcos** for contributing this image!


分析

將一個數列看成是一堆高低不一的蓄水牆,數值即這面牆的高度,求總的蓄水最大量。其實題目中的圖就已經一目瞭然了,無需過多文字說明。
針對某一個x點,決定其蓄水量應該是該點左右兩邊分別出現過的最高的牆中的最小者決定的。例如,針對A=[0,1,0,2,1,0,1,3,2,1,2,1]這個例子,A[4]=1這一點,其左邊出現過的最高牆是A[3]=2,其右邊出現過的最高牆是A[7]=3,因此兩者中的最小者就就是A[3]=2,因此A[4]的蓄水高度就是A[3]-A[4]=1,乘以底邊1,即A[4]蓄水量為1。
針對每一個點去單獨尋找這個最小值顯然是不合理的,這樣時間複雜度就是O(n*n)了。申請一個與原陣列A等長的陣列max_heights用來記錄每個點的最大蓄水量,首先從左至右遍歷一次A,記錄當前遇到過的最大值,依次填入到max_heights中。然後再從右至左遍歷一次A,也記錄當前遇到過的最大值,與max_heights中對應位置的值進行比較,如果比max_heights中對應的值小,則替換掉max_heights中的值。通過這種方法,就能用2次時間複雜度為O(n)的遍歷找出每個點的蓄水量,然後遍歷max_heights,如果比A中對應的數值大的話,就累加其差值,最後得到的就是蓄水總量。也就是說,如果A中數值對max_heights中對應數值大,說明這個點無法蓄水。
空間複雜度為O(n),時間複雜度為O(n)。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
# @param A, a list of integers
# @return an integer
def trap(self, A):
len_A = len(A)
if 1 == len_A:
return 0
max_heights = [0] * len_A
left_max = 0
for i in range(0, len_A):
if A[i] > left_max:
left_max = A[i]
max_heights[i] = left_max
right_max = 0
for i in range(len_A - 1, -1, -1):
if A[i] > right_max:
right_max = A[i]
if right_max < max_heights[i]:
max_heights[i] = right_max
result = 0
for i in range(0, len_A):
if max_heights[i] > A[i]:
result += (max_heights[i] - A[i])
return result

本文地址:https://xnerv.wang/zh-tw/leetcode-trapping-rain-water/