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.
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 Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
解题思路
用一个栈记录遍历过的关键位置,将数组进行两次遍历即可得到答案。
- 第一次从左往右遍历数组:首先将下标0添加到栈中作为初始关键节点,然后从1开始遍历。当height[i] >= height[top] (其中top代表栈顶保存的下标位置)时,说明 i 和 top 之间存在空间能够存放雨水。此时对子区间(top, i)进行遍历,统计出这段子区间中的空白区。重复这一操作直到没有找到 满足 height[i] >= height[top] 的位置i。变量 rec 记录当前栈顶保存的位置 i。
- 第二次从右往左遍历数组:首先将下标height.size()-1添加到栈中作为初始关键节点,然后从height.size()-2开始遍历,到 rec 结束。当height[i] >= height[top] (其中top代表栈顶保存的下标位置)时,说明 i 和 top 之间存在空间能够存放雨水。此时对子区间 (i, top) 进行遍历,统计出这段子区间中的空白区。
- 将两次统计出的空白区间相加就得到最后的结果。
C++代码
class Solution {
public:
int trap(vector<int>& height) {
stack<int> pos;
int sum = 0, rec = 0;
pos.push(0);
for(int i = 1; i < height.size(); i++) {
if(height[i] >= height[pos.top()]) {
for(int j = pos.top()+1; j < i; j++) {
sum += height[pos.top()] - height[j];
}
pos.push(i);
}
}
rec = pos.top();
pos.push(height.size()-1);
for(int i = height.size()-2; i >= rec; i--) {
if(height[i] >= height[pos.top()]) {
for(int j = pos.top()-1; j > i; j--) {
sum += height[pos.top()] - height[j];
}
pos.push(i);
}
}
return sum;
}
};