int trap(vector<int>& height) {
int leftmax=0,rightmax=0,res=0;
int lf=0,rh=height.size()-1;
while(lf<rh){
if(height[lf]<height[rh]){
leftmax=max(leftmax,height[lf]);
res+=leftmax-height[lf++];
}
else{
rightmax=max(rightmax,height[rh]);
res+=rightmax-height[rh--];
}
}
return res;
}
双指针方法,主要还是理解题意。
也可以用dp。