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!
给定一个数组,数组中每一个索引位表示一个bar, 对应索引位的值表示bar的高度,bar的宽度为1。计算这个bar组能盛多少水。
如图所示,次高和最高之间可以构成盛水区域。因此我们的目的就是找到所有这样的凹槽区域;
class Solution {
public:
int trap(int A[], int n) {
if(n<3)return 0;
int result=0;
int left=0;
int right=0;
int maxHeight=0; //用来保存左边界左边的最大高度
int maxIndex=-1; //用来保存左边界左边最大高度对应的索引位置
while(left<n-1){
right=left+1;
maxHeight=0;
while(right<n && A[right]<A[left]){
if(A[right]>=maxHeight){
maxHeight=A[right];
maxIndex=right;
}
right++;
}
if(right>=n){
//如果没有找到不低于左边界的右边界,则取次高bar计算
right=maxIndex;
}
//计算当前凹槽的储水量
int height=min(A[left], A[right]); //获得储水高度
for(int i=left+1; i<right; i++){
result+=height-A[i];
}
left=right;
}
return result;
}
};LeetCode: Trapping Rain Water [041],布布扣,bubuko.com
LeetCode: Trapping Rain Water [041]
原文:http://blog.csdn.net/harryhuang1990/article/details/26401675