class Solution {
public int trap(int[] height) {
/*
只要右边有比左边高的柱子,无论中间是什么情况。
当前能存的雨水量只和左边的柱子相关。
因此 ans +=max(0,left_max-height[left]);
同理,如果左边比右边的柱子高,无论中间是什么情况,
当前能存的水量为 ans +=max(0,right_max-height[right]);
左右两个指针更新左边最高和右边最高,直到相交*/
int left = 0;
int right = height.length - 1;
int left_max = 0;
int right_max = 0;
int ans = 0;
while(left <= right){
///只要右边有比左边高,无论中间是什么情况,当前所能存的雨水只和左边的最高相关.
if(left_max < right_max){
ans = ans + Math.max(0,left_max-height[left]);
left_max = Math.max(left_max,height[left]);
left++;
}else{
ans = ans + Math.max(0,right_max-height[right]);
right_max = Math.max(right_max,height[right]);
right--;
}
}
return ans;
}
}