42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) 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.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
n == height.length
0 <= n <= 3 * 104
0 <= height[i] <= 105
实现思路:
本题是一道好题,可以做的方法有动态规划还有双指针以及单调栈的方法,这里为了单独复习单调栈,所以就采用了单调栈的方法,所谓的单调栈,就是栈中所有的元素都具有单调性,本题的思路就是采用单调递减栈,将每个墙壁的坐标存入到栈中,若遇到当前的墙壁比栈顶的墙壁要矮,那当前的墙壁就入栈,因为当前的墙壁和栈顶的墙壁围起来的空间存储的水是在减少的,但是若是遍历到当前墙壁的高度大于栈顶墙壁的时候,说明当前墙壁高于栈内所有索引指向的墙壁,所以可以全部构建起装水的容器空间,于是循环出栈计算储水量。
AC代码:
class Solution {
public:
int trap(vector<int>& height) {
stack<int> st;
int idx=0,ans=0;
while(idx<height.size()) {
//如果当前墙壁高于栈顶墙壁则开始计算栈内所有墙壁和当前墙壁组成的蓄水池
while(!st.empty()&&height[idx]>height[st.top()]) {
int temp=st.top();
st.pop();
if(st.empty()) break;//如果当前墙壁的左边没有墙壁 则退出
ans+=(min(height[idx],height[st.top()])-height[temp])*(idx-st.top()-1);//计算储水量
}
st.push(idx++);
}
return ans;
}
};