42. 接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

柱状图

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:前后指针确认每个区间内的最大高度

class Solution {
    public int trap(int[] height) {
        int start = 0, end = height.length - 1;
        int[] maxHeight = new int[height.length];
        int total = 0;
        int curMaxHeight;
        while (start <= end) {
            curMaxHeight = Math.min(height[start], height[end]);
            for (int i = start; i <= end; i++) {
                maxHeight[i] = curMaxHeight;
            }
            while (start <= end && height[start] <= curMaxHeight) {
                start ++;
            }
            while (start <= end && height[end] <= curMaxHeight) {
                end --;
            }
        }
        for (int i = 0; i < height.length; i++) {
            if (height[i] < maxHeight[i]) {
                total += maxHeight[i] - height[i];
            }
        }
        return total;
    }
}
运行效率

解法二:动态规划

class Solution {
    public int trap(int[] height) {
        if (height.length == 0) {
            return 0;
        }
        // 记录每个坐标的右边最大高度
        int[] rightMaxHeight = new int[height.length];
        rightMaxHeight[height.length - 1] = height[height.length - 1];
        for (int i = height.length - 2; i >= 0; i--) {
            rightMaxHeight[i] = Math.max(rightMaxHeight[i + 1], height[i + 1]);
        }
        int leftMaxHeight = height[0];
        int total = 0;
        for (int i = 1; i < height.length; i++) {
            leftMaxHeight = Math.max(leftMaxHeight, height[i - 1]);
            int curMinHeight = Math.min(leftMaxHeight, rightMaxHeight[i]);
            if (curMinHeight > height[i]) {
                total += curMinHeight - height[i];
            }
        }
        return total;
    }
}
运行效率

你可能感兴趣的:(42. 接雨水)