[leetcode] 42. 接雨水

42. 接雨水

思路:一块柱子能接水的量取决于它左右两边最高的柱子中较短的一个。

class Solution {
    public int trap(int[] height) {
        int left[] = new int[height.length];
        int right[] = new int[height.length];
        int max = 0;
        for (int i = 0; i < height.length; i++) {
            max = Math.max(max, height[i]);
            left[i] = max;
        }
        max = 0;
        for (int i = height.length - 1; i >= 0; i--) {
            max = Math.max(max, height[i]);
            right[i] = max;
        }

        int ans = 0;
        for (int k = 1; k < height.length - 1; k++) {
            if (left[k - 1] <= 0 || right[k + 1] <= 0) continue;
            int tmp = Math.min(left[k - 1], right[k + 1]) - height[k];
            if (tmp > 0) ans += tmp;
        }

        return ans;
    }
}
posted @ 2018-07-19 23:08  ACBingo  阅读(452)  评论(0编辑  收藏  举报