Files
LeetCode/双指针/4. 接雨水.md
T
2025-09-28 23:12:58 +08:00

85 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 接雨水
## 题目
给定 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
## 思路
- 决定因素
- 左右侧最小高度 min
- 当前高度 cur
- 单位计算
- min - cur
- 累加即为答案
- 关键点
- min
- 左侧
- 右侧
- Traverse
- 1 -> n - 1
- 左侧
- n - 2 -> 0
- 右侧
- 约定
- `leftMax = height[0]`
- `rightMax = height[n - 1]`
## 代码
```java
class Solution {
public int trap(int[] height) {
int n = height.length;
int ans = 0;
if (n == 0) {
return 0;
}
int[] leftMax = new int[n];
leftMax[0] = height[0];
int[] rightMax = new int[n];
rightMax[n - 1] = height[n - 1];
// Traverse 1
for (int i = 1; i < n; i++) {
leftMax[i] = Math.max(leftMax[i - 1], height[i]);
}
// Traverse 2
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = Math.max(rightMax[i + 1], height[i]);
}
// Count
for (int i = 0; i < n; i++) {
ans += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return ans;
}
}
```