【力扣刷题】42. 接雨水-单调栈

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

 

示例 1:

 

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

输入:height = [4,2,0,3,2,5]
输出:9

 

提示:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

注意:在st.pop()后要留意是否检查!st.empty(),

class Solution {
public:
    int trap(vector<int>& height) {
        int l=0,r=height.size();
        int ans=0;
        stack<int>st;
        st.push(0);
        for(int i=1;i<r;i++){
            int tem=height[i];
            if(tem<height[st.top()]){
                st.push(i);
            }else if(tem==height[st.top()]){
                st.pop();
                st.push(i);
            }else{
                while(!st.empty()&&tem>height[st.top()]){
                    int bottom=st.top();
                    st.pop();
                    if(!st.empty()){
                        int h=min(tem,height[st.top()])-height[bottom];
                        int w=i-st.top()-1;
                        ans+=h*w;
                    }
                }
                st.push(i);
            }
        }
        return ans;
    }
};

 

版权声明:
作者:Zhang, Hongxing
链接:http://zhx.info/archives/614
来源:张鸿兴的学习历程
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录