力扣P42 接雨水
这个题还是挺简单的

class Solution {
public:
int trap(vector<int>& height) {
int l = 0, r = height.size() - 1;
int lmax = 0,rmax = 0,ans = 0;
while(l < r){
lmax = max(lmax, height[l]);
rmax = max(rmax, height[r]);
if(lmax <= rmax){
ans += lmax - height[l];
l++;
}else{
ans += rmax - height[r];
r--;
}
}
return ans;
}
};

求每个位置的左右遍历到的最大值,这个位置能接到的雨水就是左右最大值的最小值减去当前位置的高度,移动左右指针直到重合就遍历了所有位置能接到的雨水 ,时间复杂度O(n)。