接雨水(单调递减栈)

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

 示例 1:

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6

示例 2:

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

思路:使用单调递减栈,当遍历到的heght数组元素大于栈顶元素对应的高时,说明形成低洼,计算此时能接住的雨水,并不断累积直至数组元素遍历完毕。



class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> index;
        int res = 0;
        for(int i=0;i<height.size();i++){
            while(!index.empty()&&height[i]>height[index.top()]){//形成低洼
                int j = index.top();
                index.pop();
                if(!index.empty()){
                    h = min(height[i],height[index.top()])-height[j];
                    w = i-index.top()-1
                    res += w*h;
                }
            }
            index.push(i);
        }
        return res;
    }
};

 

posted on 2024-12-17 18:25  _月生  阅读(18)  评论(0)    收藏  举报