Day49
42. 接雨水
思路
这道题利用单调栈进行横向求解。对于每一个元素,找到它右边第一个比它大的元素和左边第一个比它大(或者与它相等的元素,当然这种情况可以忽略),最后计算雨水的存储量:((左右两边的高度差)减去(中间元素的高度))乘上中间元素的宽度。为什么要乘中间元素的宽度?因为中间元素可能不止一个。
代码
class Solution {
public:
int trap(vector<int>& height) {
// if(height.size() <= 2) return 0; //加不加都可以,最好加上
stack<int> st;
st.push(0);
int sum;
for(int i = 1; i < height.size(); i++){ //直接从第二个元素开始遍历
if(height[i] < height[st.top()]) st.push(i);
else if(height[i] == height[st.top()]){
st.pop();
st.push(i);
}
else{
while(!st.empty() && height[i] > height[st.top()]){
int mid = st.top();
st.pop();
if(!st.empty()){ //如果这里是true,会发生什么?
int h = min(height[st.top()], height[i]) - height[mid];
int w = i - st.top() - 1;
sum += h * w;
}
}
st.push(i);
}
}
return sum;
}
};
等等