问题
https://leetcode.com/problems/trapping-rain-water/
代码
class Solution {
public:
int trap(vector<int>& height) {
int L = 0;
int R = height.size()-1;
int ret = 0;
int maxL = 0;
int maxR = 0;
while(L < R)
{
if (height[L] <= height[R]){
if (height[L] > maxL) maxL = height[L];
else ret+= (maxL-height[L]);
++L;
}else{
if (height[R] > maxR) maxR = height[R];
else ret+= (maxR-height[R]);
--R;
}
}
return ret;
}
};
代码分析:
要求得位置i处的雨水量需要找到下面两种情形:
第一种是在0~i最大值为h[k] = maxL, 且在i的右边有h[j] > h[k];
第二种是在i~n 最大值为h[j] = maxR, 且k< i , h[k] > h[j];
循环保证了h[L] 或h[R] 是当前遍历过数中的最大值。
代码中循环维护了maxL 和maxR值。并且如果height[L] <= height[R] 说明满足第一种情况(height[R] 是遍历过数中的最大值, maxL< height[R]) , 否则满足条件二。
236

被折叠的 条评论
为什么被折叠?



