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

这道题看图很好理解,题目意思就不赘述了。

第一次的想法是,先遍历最大的一个数,然后以此为分界点,前后分别求出面积,然后减去本身的高度,就是所求答案。

 

package leetcode;

public class trap {
	public int trap(int[] height) {
	  int len = height.length;
          if(len < 2)
              return 0;
          int max = 0, pos = 0;
          for( int i = 0; i<len ; i++){
        	if(max < height[i]){
        		max = height[i];
        		pos = i;
        	}
          }
          int b_pos = 0,a_pos = len-1;
          int all = 0;
          for( int i = 0; i<=pos ; i++){
          	if( height[i]>=height[b_pos] ){
        		all+=height[b_pos]*(i - b_pos);
        		b_pos = i;
        	}
        	all-=height[i];
          }
          for( int i = len-1;i>=pos;i--){
          	if( height[i]>=height[a_pos] ){
        		all+=height[a_pos]*(a_pos - i);
        		a_pos = i;
        	}
        	all-=height[i];
          }
       
          return all+height[pos];
    }
}

 但是结果并没有达到最优,总体思想有一些微变,就达到了最佳。时间复杂度o(n)。空间复杂度1。

package leetcode;

public class trap {
	public int trap(int[] height) {
		int len = height.length;
		if (len < 2)
			return 0;
		int be = 0, af = len - 1, result = 0;
		int po1 = 0, po2 = len - 1;
		while (be < af) {
			if (height[po1] <= height[af]) {
				while (be < af && height[be] <= height[po1]) {
					result -= height[be];
					be++;
				}
				result += height[po1] * (be - po1);
				po1 = be;
			} else {
				while (af > be && height[af] <= height[po2]) {
					result -= height[af];
					af--;
				}
				result += height[po2] * (po2 - af);
				po2 = af;
			}
		}
		return result;

	}
}