示例代码 登录后复制 class Solution { public: int trap(vector<int>& height) { int res=0; int leftMax=0,rightMax=0; int left=0,right=height.size()-1; while(left<right){ leftMax=max(leftMax,height[left]); rightMax=max(rightMax,height[right]); //判断左右两边哪个值比较小,然后再用其对应侧的最大值减去较小的一边的值,就可以得到当前位置存的雨水的高度 if(height[left]<height[right]){ res+=leftMax-height[left]; left++; }else{ res+=rightMax-height[right]; right--; } } return res; } }; 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26. 效果展示 原创作者: u_15305087 转载于: https://blog.51cto.com/u_15305087/11517896