1. 程式人生 > >接雨水

接雨水

給定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。
在這裡插入圖片描述

上面是由陣列 [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
(1)
方法:雙指標法
思路:
1,先找到陣列中最大元素以及最大元素的位置;
2,然後從最大元素位置處分開,從兩端開始遍歷;
3,雨水儲存是遞增的,雨水量是遍歷過程中陣列大的元素減去小的元素的值的和;比如上圖
先找到最大值為3,位置為7,然後遍歷左邊,首先索引1處的值大,那麼leftMax = 1,到索引2時變為0,那麼面積area = 0 + 1 - 0=1;繼續走,索引3的值2,大於1,這時就將leftMax=2,在索引4到6(包含)的值都比2小,所以面積就是area = 1 + (2-1)+ (2-0)+(2-1)= 5;在走就到了7,也就是索引最大處,那麼左端就遍歷完成了,在遍歷從陣列最右端到7這一段,思路一致,就可以的到area=5+1=6;拿到結果;
4,對特殊情況記得判斷即可;

class Solution {
    public int trap(int[] height) {
        //特殊情況
        if (height == null || height.length <= 2)
            return 0;
        //先求得陣列最大值和最大值所在的索引
        int max = -1, maxInd = 0;
        for (int i = 0; i < height.length; i++) {
            if (height[i] > max) {
                max = height[i];
                maxInd = i;
            }
        }
        //然後從陣列兩端開始遍歷,求面積
        int area = 0;
        for (int i = 0, root = height[0]; i < maxInd; i ++) {
            if (height[i] > root)
                root = height[i];
            else
                area += root - height[i];
        }
        for (int i = height.length - 1, root = height[height.length - 1]; i > maxInd; i --) {
            if (height[i] > root)
                root = height[i];
            else
                area += root - height[i]; 
        }
        return area;
    }
}

(2)
思路:對前一個方法優化,沒必要先求陣列最大值,只需要將陣列從左右兩端進行移動,左右指標那個的值大就移動那個指標,直到遍歷完成整個陣列,求解思路和上面一致的。

class Solution {
    public int trap(int[] height) {
        if (height.length <= 2 || height == null) return 0;
        int left = 0, right = height.length - 1;
        int area = 0;
        int leftMax = 0, rightMax = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] >= leftMax) 
                    leftMax = height[left];
                else 
                    area += leftMax - height[left];
                ++left;
            }
            else {
                if (height[right] >= rightMax) 
                    rightMax = height[right];
                else
                    area += rightMax - height[right];
                --right;
            }
        }
        return area;
    }
}