Hard
题目描述
给定 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.length1 <= n <= 2 * 10^40 <= height[i] <= 10^5
解题思路
解题思路
这是一道经典的动态规划和双指针问题,有多种解法:
方法一:动态规划(推荐)
对于每个位置 i,能接到的雨水量取决于其左侧和右侧的最大高度的最小值减去当前位置的高度。核心思路是:
left_max[i]:位置 i 左侧(包括 i)的最大高度right_max[i]:位置 i 右侧(包括 i)的最大高度- 位置 i 的积水量:
min(left_max[i], right_max[i]) - height[i]
方法二:双指针优化
基于动态规划的思路,我们可以用双指针来优化空间复杂度。使用两个指针分别从左右两端向中间移动,同时维护左侧最大值和右侧最大值。
方法三:单调栈
维护一个递减的单调栈,当遇到比栈顶更高的柱子时,说明可以形成凹槽接水。
这里给出双指针解法,它具有 O(1) 的空间复杂度且思路清晰。
代码实现
class Solution {
public:
int trap(vector<int>& height) {
int left = 0, right = height.size() - 1;
int leftMax = 0, rightMax = 0;
int result = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
result += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
result += rightMax - height[right];
}
right--;
}
}
return result;
}
};
class Solution:
def trap(self, height: List[int]) -> int:
left, right = 0, len(height) - 1
left_max = right_max = result = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
result += left_max - height[left]
left += 1
else:
if height[right] >= right_max:
right_max = height[right]
else:
result += right_max - height[right]
right -= 1
return result
public class Solution {
public int Trap(int[] height) {
int left = 0, right = height.Length - 1;
int leftMax = 0, rightMax = 0;
int result = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
result += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
result += rightMax - height[right];
}
right--;
}
}
return result;
}
}
var trap = function(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let result = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
result += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
result += rightMax - height[right];
}
right--;
}
}
return result;
};
复杂度分析
| 复杂度类型 | 双指针解法 | 动态规划解法 |
|---|---|---|
| 时间复杂度 | O(n) | O(n) |
| 空间复杂度 | O(1) | O(n) |
相关题目
. Container With Most Water (Medium)
. Product of Array Except Self (Medium)
. Trapping Rain Water II (Hard)
. Pour Water (Medium)