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.
例子:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
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
leftmax=Math.max(leftmax,A[a]);
//更新rightmax
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;
}