1. 程式人生 > 實用技巧 >LeetCode 42 接雨水

LeetCode 42 接雨水

LeetCode42 接雨水

題目描述

給定 n 個非負整數表示每個寬度為 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 個單位的雨水(藍色部分表示雨水)。
輸入:height = [4,2,0,3,2,5]
輸出:9

演算法分析

單調棧

  • 棧裡面存的是下標
  • 我們存的是單調下降的一個結構,如何發現height[stack.peek()] <= height[i]棧頂元素小於當前
    • 計算凹槽的面積,棧頂高度-上一個位置的高度 * 寬
  • 最後,如果棧不為空,說明當前高度小於等於棧頂高度
    • 計算凹槽 h[i] - last * 寬

時間複雜度

只掃描了一邊陣列

\(O(n)\)

Java程式碼

class Solution {
    public int trap(int[] height) {
        Stack<Integer> stack = new Stack<Integer>();
        int res = 0;
        for(int i = 0; i < height.length; i ++){
            int last = 0;
            while(stack.size() != 0 && height[stack.peek()] <= height[i]){
                res += (height[stack.peek()] - last) * (i - stack.peek() - 1);
                last = height[stack.peek()];
                stack.pop();
            }
            
            if(stack.size()!=0){
                res += (i - stack.peek() - 1) * (height[i] - last);
            }

            stack.push(i);
        }

        return res;
    }
}