1. 程式人生 > 其它 >演算法-接雨水

演算法-接雨水

技術標籤:演算法演算法leetcode

給定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。
示例 1:
在這裡插入圖片描述
輸入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
輸出:6
解釋:上面是由陣列 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。

 /**
     * 所以我們可以認為如果一端有更高的條形塊(例如右端),積水的高度依賴於當前方向的高度(從左到右)。當我們發現另一側(右側)的條形塊高度不是最高的,我們則開始從相反的方向遍歷(從右到左)。
     * 我們必須在遍歷時維護 \text{left\_max}left_max 和 \text{right\_max}right_max ,但是我們現在可以使用兩個指標交替進行,實現 1 次遍歷即可完成。
     * @param height
     * @return
     */
public int trap(int[] height) { int left = 0, right = height.length - 1; int ans = 0; int left_max = 0, right_max = 0; while (left < right) { if (height[left] < height[right]) { if (height[left] >= left_max) { left_max =
height[left]; } else { ans += (left_max - height[left]); } ++left; } else { if (height[right] >= right_max) { right_max = height[right]; } else { ans +=
(right_max - height[right]); } --right; } } return ans; }