Description
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.
Example
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
思路
- 最开始用一个栈实现,16ms,思路有点复杂了
- 栈里存的是小于当前最大值的元素。比如最开始是0,然后当前最大值是0,遇到1后出栈,然后1入栈,然后存0,然后遇到2,全部出栈,2入栈。。在这个过程中计算存水量
- 思路2:借鉴11题的思路。
代码
class Solution {
public:
int trap(vector<int>& height) {
int len = height.size();
int left = 0;
int right = len - 1;
int sum = 0;
while (left < right)
{
int m = min(height[left], height[right]);
if (height[left] == m)
{
while (++left < right && height[left] < m)
sum += m - height[left];
}
else{
while (left < --right && height[right] < m)
sum += m - height[right];
}
}
return sum;
}
};