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
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcosfor contributing this image!
用单调栈做出来了 算是最普通的解法了 但是还是搞得有点复杂
solution里有一个双指针的解法 挺好的 也不难
时间复杂度是最佳 O(n) 空间复杂度也是最佳 O(1) 值得学习
int trap(vector<int> height)
{
int left = 0, right = height.size() - 1;
int ans = 0;
int left_max = 0, right_max = 0;
while (left < right) {
if (height[left] < height[right]) {
height[left] >= left_max ? (left_max = height[left]) : ans += (left_max - height[left]);
++left;
}
else {
height[right] >= right_max ? (right_max = height[right]) : ans += (right_max - height[right]);
--right;
}
}
return ans;
}
这个想法大概是这样的 在输入的数组中 当有一个点可以存水的时候 必然是这个点的高度比两边低
那么这个点存水的量 由两边的哪个边决定呢?是由两边中比较低的一边决定的
比如上图array中的1,2,3三个点 高度分别是1,0,2
比如上图array中的1,2,3三个点 高度分别是1,0,2
最后2点的存水量 就是由比较低的一边 也就是1点的高度决定的
所以我们可以维护一个leftMax 存最高的高度 当height[left]<leftMax 而height[left]<height[right]时 说明height[left]小于两边 也就是一个凹陷 可以存水
存水的量 则由leftMax和height[right]中比较低的点 也就是leftMax决定