42. Trapping Rain Water(直方图 存水量 hard)

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.

 1 class Solution {
 2     public int trap(int[] height) {
 3         int left = 0;
 4         int right = height.length-1;
 5         int trap = 0;
 6         int h = 0;
 7         while(left<right){
 8             if(height[left]<height[right]){
 9                 h = Math.max(height[left],h);
10                 trap+=(h - height[left]);
11                 left++;
12             }
13             else{
14                 h = Math.max(height[right],h);
15                 trap+=(h - height[right]);
16                 right--;
17                 
18             }
19         }
20         return trap;
21     }
22 }
原文地址:https://www.cnblogs.com/zle1992/p/8465709.html