给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例 1:

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
示例 2:
输入:height = [4,2,0,3,2,5]
输出:9
核心思路:
- 左指针(
left)指向左端,右指针(right)指向右端。- 我们维护两个变量:
left_max和right_max,分别记录当前左端和右端的最大高度。- 由于右端最大高度不会变小,所以当
left_max小于等于right_max时,可以确定左侧的柱子能够接住的雨水量就是left_max - height[left],然后将左指针向右移动。- 反之,当
right_max小于left_max时,雨水量则由right_max决定,并移动右指针向左。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
int trap(vector<int>& height)
{
if (height.size() == 0)
return -1;
int left = 0;
int right = height.size() - 1;
int left_max = 0;
int right_max = 0;
int total_water = 0;
while (left < right)
{
if (height[left] <= height[right])
{
left_max = max(left_max, height[right]);
total_water += left_max - height[left];
left++;
}
else
{
right_max = max(right_max, height[left]);
total_water += right_max - height[right];
right--;
}
}
return total_water;
}
};
int main()
{
Solution solution;
vector<int> height1 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
vector<int> height2 = { 4, 2, 0, 3, 2, 5 };
cout << "Test case 1: " << solution.trap(height1) << endl;
cout << "Test case 2: " << solution.trap(height2) << endl;
return 0;
}
2846

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



