class Solution {
public int trap(int[] height) {
if(height.length<3){
return 0;
}
int left=0,right=height.length-1;
int leftmax=height[left],rightmax=height[right];
int res=0;
while(left<right){
if(leftmax<rightmax){
res+=leftmax-height[left++];
leftmax=Math.max(leftmax,height[left]);
}else{
res+=rightmax-height[right--];
rightmax=Math.max(rightmax,height[right]);
}
}
return res;
}
}
确实是想不到的,核心思想是左右最高中较小的高度减去当前位置的高度,就是该位置的储水量。