首先直观解法
,位置 i处可以接到的雨水量为 min(l_max[i], r_max[i]) * height[i], 然后res累计这个量,最后加和完的结果就是一共可以接的雨水量。
class Solution {
public:
int trap(vector<int>& height) {
int res = 0;
int n = height.size();
vector<int> l_max(n);
vector<int> r_max(n);
l_max[0] = height[0];
r_max[n - 1] = height[n - 1];
for( int i = 1; i < n; i ++)
l_max[i] = max(height[i], l_max[i - 1]);
for( int i = n - 2; i >= 0 ; i --)
r_max[i] = max(height[i], r_max[i + 1]);
for( int i = 0; i < n; i ++)
res += min(l_max[i], r_max[i]) - height[i];
return res;
}
};
双指针
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int left = 0, right = n - 1;
int l_max = height[0], r_max = height[n - 1];
int res = 0;
while( left < right ){
l_max = max(l_max, height[left]);
r_max = max(r_max, height[right]);
if( l_max < r_max ){
res += (l_max - height[left]);
left ++;
}
else{
res += (r_max - height[right]);
right --;
}
}
return res;
}
};