https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode-solution-tuvc/
1. 题目描述
https://leetcode-cn.com/problems/trapping-rain-water/
2. 解题思路
2.1. 动态规划
对于下标 ii,下雨后水能到达的最大高度等于下标 ii 两边的最大高度的最小值,下标 ii 处能接的雨水量等于下标 ii 处的水能到达的最大高度减去 \textit{height}[i]height[i]。
朴素的做法是对于数组 \textit{height}height 中的每个元素,分别向左和向右扫描并记录左边和右边的最大高度,然后计算每个下标位置能接的雨水量。假设数组 \textit{height}height 的长度为 nn,该做法需要对每个下标位置使用 O(n)O(n) 的时间向两边扫描并得到最大高度,因此总时间复杂度是 O(n2)O(n2)。
class Solution {
public int Trap(int[] height) {
int n = height.length;
if (n == 0) {
return 0;
}
int[] leftMax = new int[n];
leftMax[0] = height[0];
for (int i = 1; i < n; ++i) {
leftMax[i] = Math.Max(leftMax[i - 1], height[i]);
}
int[] rightMax = new int[n];
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; --i) {
rightMax[i] = Math.Max(rightMax[i + 1], height[i]);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += Math.Min(leftMax[i], rightMax[i]) - height[i];
}
return ans;
}
}
复杂度分析
时间复杂度:O(n)O(n),其中 nn 是数组 \textit{height}height 的长度。计算数组 \textit{leftMax}leftMax 和 \textit{rightMax}rightMax 的元素值各需要遍历数组 \textit{height}height 一次,计算能接的雨水总量还需要遍历一次。
空间复杂度:O(n)O(n),其中 nn 是数组 \textit{height}height 的长度。需要创建两个长度为 nn 的数组 \textit{leftMax}leftMax 和 \textit{rightMax}rightMax
2.1. 单调栈
class Solution {
public int Trap(int[] height) {
int ans = 0;
Stack<int> stack = new Stack<int>();
int n = height.Length;
for (int i = 0; i < n; ++i) {
while (stack.Count!=0 && height[i] > height[stack.Peek()]) {
int top = stack.Pop();
if (stack.Count==0) {
break;
}
int left = stack.Peek();
int currWidth = i - left - 1;
int currHeight = Math.Min(height[left], height[i]) - height[top];
ans += currWidth * currHeight;
}
stack.Push(i);
}
return ans;
}
}
2.3. 双指针
当两个指针相遇时,即可得到能接的雨水总量。
public class Solution {
public int Trap(int[] height) {
int left = 0, right = height.Length - 1;
int ans = 0;
int left_max = 0, right_max = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= left_max) {
left_max = height[left];
} else {
ans += (left_max - height[left]);
}
++left;
} else {
if (height[right] >= right_max) {
right_max = height[right];
} else {
ans += (right_max - height[right]);
}
--right;
}
}
return ans;
}
}
ght[right]);
}
--right;
}
}
return ans;
}
}