class Solution {
public:
int trap(vector<int>& height) {
int l = 0, r = height.size() - 1;
int lmax = 0, rmax = 0;
int res = 0;
while(l < r){
if(height[l] < height[r]){ //右边界高
if(height[l] < lmax){ //当前位置小于左边最高
res += lmax - height[l]; //更新一个地方的水量
}else{
lmax = height[l];
}
++l;
}else{
if(height[r] < rmax){ //右边界高
res += rmax - height[r]; //当前位置小于右边最高
}else{
rmax = height[r];
}
--r;
}
}
return res;
}
};
LeetCode 42. 接雨水
最新推荐文章于 2024-09-14 22:25:23 发布