42. Trapping Rain Water

class Solution {
    public int trap(int[] height) {
      if (height == null || height.length == 0){
        return 0;
      }

      int[] left = new int[height.length];
      int[] right = new int[height.length];
      int result = 0;
 
      
      left[0] = height[0];
      for(int i = 1; i < height.length; i++){
        left[i] = Math.max(height[i], left[i-1]);
      }
      
      right[height.length - 1] = height[height.length - 1];
      for(int i = height.length - 2; i >= 0; i--){
        right[i] = Math.max(height[i], right[i+1]);
      }
      
      for(int i = 0; i < height.length; i++){
        result += Math.min(right[i], left[i]) - height[i];
      }
      return result;
    }
}

 

space optimization

这个计算就是多了个心眼, 用我妈的话来说, 用leftmax 时不用计算另一半, 是因为left Max比 right Max小的时候, 如果像上一个方法, 我们还是取两个中最小的

, 那么我们就不用知道rightMax具体是多少, 反正我们知道比left Max 大 

Using 2 pointers

Keep track of the maximum height from both forward directions backward directions, call them leftmax and rightmax.

public int trap(int[] A){
    int a=0;
    int b=A.length-1;
    int max=0;
    int leftmax=0;
    int rightmax=0;
    while(a<=b){
        leftmax=Math.max(leftmax,A[a]);
        rightmax=Math.max(rightmax,A[b]);
        if(leftmax<rightmax){
            max+=(leftmax-A[a]);       // leftmax is smaller than rightmax, so the (leftmax-A[a]) water can be stored
            a++;
        }
        else{
            max+=(rightmax-A[b]);
            b--;
        }
    }
    return max;
}

 

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.


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. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

posted on 2018-07-18 08:55  猪猪&#128055;  阅读(161)  评论(0)    收藏  举报

导航