. - 力扣(LeetCode)
42. 接雨水
困难
相关标签
相关企业
给定 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
提示:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
vector<int> left(n, 0);
vector<int> right(n, 0);
int left_max = 0;
int right_max = 0;
for (int i = 0; i < n; i++) {
left_max = std::max(left_max, height[i]);
left[i] = left_max;
}
for (int i = n - 1; i >= 0; i--) {
right_max = std::max(right_max, height[i]);
right[i] = right_max;
}
int ret = 0;
for (int i = 0; i < n; i++) {
ret += (std::min(left[i], right[i]) - height[i]);
}
return ret;
}
};
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int left = 0;
int right = n - 1;
int area = 0;
int max_left = 0;
int max_right = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] > max_left) {
max_left = height[left];
} else {
area += (max_left - height[left]);
}
left++;
continue;
}
if (height[right] > max_right) {
max_right = height[right];
} else {
area += (max_right - height[right]);
}
right--;
}
return area;
}
};