42. Trapping Rain Water

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

For example,

Given`[0,1,0,2,1,0,1,3,2,1,2,1]`, return`6`.

The above elevation map 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.

思路

  1. 分别用2个数组leftHeight, rightHeight分别记录当前index,它左边的最大值和右边的最大值。
  2. 那么当前index的可以盛水量 == (min(leftHeight[i], rightHeight[i]) - height[i]) * 1. 因为盛水量有矮的墙决定,而且每个index有自己的高度,所以必须减去他自身的高度。
    Note:如果盛水量< 0,说明无法盛水,那么volume = 0
  3. 如果获取leftHeight, rightHeight? 自左向右遍历数组, 找到leftHeight; 自右向左遍历数组,找到rightHeight。
class Solution {
    public int trap(int[] height) {
        if (height == null || height.length == 0) {
          return 0;
        }
    
        int len = height.length;
        int[] leftHeight = new int[len];
        int[] rightHeight = new int[len];

        int leftMax = 0;
        leftHeight[0] = 0;
        //1. 从左向右找当前index左边最大值,一旦找到当前最大值,其后的所有最大值都是这个最大值,直到找到更大的
        for (int i = 1; i < len; i++) {
          if (height[i - 1] > leftMax) {
                leftMax = height[i - 1];
              } 
            leftHeight[i] = leftMax;
        }
        
        //2. 从右向左找当前index右边最大值,一旦找到当前最大值,其后的所有最大值都是这个最大值,直到找到更大的
        int rightMax = 0;
        rightHeight[len - 1] = 0;
        for (int i = len - 2; i >= 0; i--) {
          if (height[i + 1] > rightMax){
            rightMax = height[i + 1];
          }
          rightHeight[i] = rightMax;
        }
    
        //3. 计算容量
        int result = 0;
        for (int i = 0; i < len; i++) {
          int waterTrap = Math.min(leftHeight[i], rightHeight[i]) - height[i];
          result += waterTrap > 0 ? waterTrap : 0;
        }
        return result;
    }
}

你可能感兴趣的:(42. Trapping Rain Water)