1. 程式人生 > >LeetCode 接雨水

LeetCode 接雨水

題目來源:https://leetcode-cn.com/problems/trapping-rain-water/

今天在LeetCode上看到一道很有意思的題目:接雨水。

題目給出了一些柱子的高度,然後要求出這些柱子可以裝的水有多少。

figure_1

我想到的方法是從左往右遍歷陣列,記錄當前的最高的柱子高度,只要遇到比最高柱子低的柱子,就假設這個柱子可以裝下(最高柱子高度 - 較低柱子高度)的水。一遍遍歷後,就會發現

figure_2

圖中綠色部分也會被記錄下來,而實際上這部分是不能裝水的,所以這時再從最後往前遍歷陣列,將多餘的部分去掉,直到遇到最高的柱子為止。

python3 程式碼如下:

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        num = 0
        h = 0
        for i in range(len(height)):
            if height[i] >= h:
                h = height[i]
            else:
                num += h - height[i]
        i = len(height)-1
        small = 0
        while i >= 0:
            if h == height[i]:
                break
            if small < height[i]:
                small = height[i]
                num -= (h - small)
                i -= 1
                continue
            if height[i] < h and height[i] > small:
                num -= (h - height[i])
            elif height[i] <= small:
                num -= (h - small)
            
            i -= 1
        return num