Problem: 42. 接雨水
思路
很多解法
解题方法
只需分别计算每个格子能承接的雨水即可,每个格子能接的雨水取决于它左右两侧最高的格子,再使用双指针遍历,即可。
Code
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int l = 0;
int r = n - 1;
int ans = 0;
int lmax = height[l];
int rmax = height[r];
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;
}
};
class Solution {
public int trap(int[] height) {
int n = height.length;
int ans = 0;
int l = 0;
int r = n-1;
int left = 0;
int right = 0;
while(l < r){
left = Math.max(left, height[l]);
right = Math.max(right, height[r]);
if(height[l] < height[r]){
ans += left - height[l];
l++;
}
else{
ans += right - height[r];
r--;
}
}
return ans;
}
}