相关问题
11. Container With Most Water
42. Trapping Rain Water
407. Trapping Rain Water II
Discription
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
思路
双指针:用两个指针分别表示容器的左边界 left 和右边界 right。
选取 height[left] 和 height[right] 中较短的边,不妨设 minH = height[left] <= height[right]。
向右移动left,可能出现如下两种情况:
- height[left + 1] > minH。则重新选择瓶颈边并更新 minH;
- height[left + 1] <= minH。即 height[left + 1] <= height[left] 且 height[left + 1] <= height[right]。由 minH 的更新过程可知, minH 为 left + 1 以左最高边界高度, 且 height[left] 为瓶颈边,故在 left + 1 处可蓄水 minH - height[left + 1]。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码
class Solution {
public:
//双指针
int trap(vector<int>& height) {
if (height.empty()) return 0;
int left = 0, right = height.size() - 1;
int sum = 0;
while (left < right)
{
int minH = min(height[left], height[right]);
if (height[left] <= height[right])
{
left++;
while (left < right && height[left] <= minH)
{
sum += minH - height[left];
left++;
}
}
else
{
right--;
while (left < right && height[right] <= minH)
{
sum += minH - height[right];
right--;
}
}
}
return sum;
}
};
特殊样例
{4, 1, 0, 2}
从局部看{1, 0, 2}的两条边界高度为
1,2
,其储水量为
min(1,2)−0=1
但从整体看,边界高度为
4,2
,其储水量为
1+2=3
。