接雨水
给定 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
- 0 <= n <= 3 * 104
- 0 <= height[i] <= 105
https://leetcode-cn.com/problems/trapping-rain-water
该位置最多能装1格水。它的左边最大的高度是l_max = 2格,它的右边最大高度为r_max = 3格,所以决定该位置水的最大高度为min(l_max,r_max) = 2,又因为该位置高度height[i] = 1,所以最多可以装min(l_max,r_max) - height[i] = 2 - 1 = 1格水。
class Solution {
public:
int trap(vector<int>& height) {
int i, len = height.size(), l_max, r_max, sum = 0;
for(i=1;i<len-1;i++){
l_max = 0;
r_max = 0;
//找左边最高的柱子
for(int j=i; j>=0; j--)
l_max = max(l_max, height[j]);
//找右边最高的柱子
for(int j=i; j<len; j++)
r_max = max(r_max, height[j]);
sum += min(l_max, r_max) - height[i];
}
return sum;
}
};
之后便是优化代码,因为这个代码会超时。
动态规划
提前存储每个位置上所有所有柱子高度的最大值和所有右边柱子高度的最大值 。
可以开两个数组l_max和r_max来充当备忘录。
l_max[i]表示第i个位置上的元素,它的左边最高的柱子高度
r_max[i]表示第i个位置上的元素,它的右边最高的柱子高度
class Solution {
public:
int trap(vector<int>& height) {
//判断height是否为空,也就是height = []
if(height.empty()) return 0;
int i, len = height.size(), sum = 0;
vector<int> l_max(len), r_max(len); //创建备忘录
//初始化
l_max[0] = height[0];
r_max[len - 1] = height[len - 1];
//从左向右计算出l_max[i]
for (i = 1; i<len; i++)
l_max[i] = max(l_max[i - 1], height[i]);
//从右向左计算出r_max[i]
for (i = len - 2; i >= 0; i--)
r_max[i] = max(r_max[i + 1], height[i]);
//计算可以接到雨水的总量
for (i = 1; i<len - 1; i++)
sum += min(l_max[i], r_max[i]) - height[i];
return sum;
}
};
动态规划复杂度分析:
- 时间复杂度O(n)
- 空间复杂度O(n)
单调栈
class Solution {
public:
int trap(vector<int>& height)
{
int ans = 0, current = 0;
stack<int> s;
while (current < height.size()) {
while (!s.empty() && height[current] > height[s.top()]) {
int top = s.top();
s.pop();
//前面进行了压出栈操作,可能会出现栈为空的情况
if (s.empty())
break;
int distance = current - s.top() - 1; //注意①:不能是current - top
int bounded_height = min(height[current], height[s.top()]) - height[top];
ans += distance * bounded_height;
}
s.push(current++);
}
return ans;
}
};
举个例子
输入: [3,0,2,1,0,2,3]
输出: 10
双指针解法
因为只在乎min(l_max, r_max),若l_max < r_max,那么水的最高高度就由l_max来决定,至于r_max是否是left指针右边最高的柱子,不重要,重要的是height[i]能够装的水只和l_max有关。
LeetCode官方视频讲解:
https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
class Solution {
public:
int trap(vector<int>& height)
{
if(height.empty())
return 0;
int len = height.size();
int left = 0, right = len - 1;
int sum = 0;
int l_max = height[0];
int r_max = height[len-1];
while(left<=right){
l_max = max(l_max, height[left]);
r_max = max(r_max, height[right]);
if(l_max < r_max){
sum += l_max - height[left];
left++;
}
else{
sum += r_max - height[right];
right--;
}
}
return sum;
}
};