【算法】【线性表】Trapping Rain Water(接水量)

发布时间 2023-12-26 07:29:10作者: 酷酷-

1  题目

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

2  解答

2.1  比较好理解的

总的接水量 = 每个元素的接水量的和,而每个元素的接水量 = min(leftMax, rightMax) - 自己

class Solution {
    public int trap(int[] height) {
        // 记录总的接水量
        int res = 0;
        // 总的接水量 = 每个元素的接水量的和
        // 每个元素的接水量 = min(leftMax, rightMax) - 自己
        // 求每个元素的左侧最大值
        int len = height.length;
        int[] leftMax = new int[len];
        leftMax[0] = height[0];
        for (int i=1; i<len; i++) {
            leftMax[i] = Math.max(leftMax[i-1], height[i]);
        }
        // 求每个元素的右侧最大值
        int[] rightMax = new int[len];
        rightMax[len-1] = height[len-1];
        for (int i=len-2; i>=0; i--) {
            rightMax[i] = Math.max(rightMax[i+1], height[i]);
        }
        // 计算每个元素的接水量
        for (int i=0; i<len; i++) {
            res += Math.min(leftMax[i], rightMax[i]) - height[i];
        }
        return res;
    }
}