leetcode - 42. Trapping Rain Water

题目描述如下
在这里插入图片描述
在这里插入图片描述
思路:
用一个栈来储存之前遍历过的并对之后有用的bar的位置。
对之后有用的bar应该具有的特征为比在此元素之后入栈的所有bar的高度都高。(因为如果比之后的bar的高度还低,那么它对当前bar的储水能力并无影响。
在遍历所有bar的时候,若当前bar比栈顶的bar还要低,那么直接入栈,如果比栈顶元素所指向的bar的高度还要高,则要进行出栈操作,并在出栈时,计算改bar与当前bar之间的水的容积(不包括之前出栈的bar与当前bar所围的水的容积)

class Solution {
public:
    int trap(vector<int>& height) {
        stack<int>a;
        int i,n=height.size();
        if(n<3) return 0;
        int pre=height[0],contain(0);
        
        a.push(0);
        for(i=1;i<n;++i)
        {
            if(height[i]>pre)
            {
                while(!a.empty()&&height[a.top()]<=height[i])
                {
                    contain+=(i-a.top()-1)*(height[a.top()]-pre);
                    pre=height[a.top()];
                    a.pop();
                    
                }
                if(!a.empty())
                {
                    contain+=(i-a.top()-1)*(height[i]-pre);
                }
            }
            a.push(i);
            pre=height[i];
        }
        return contain;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41938758/article/details/88854897