【leetcode 单调栈 C++】42. Trapping Rain Water

42. Trapping Rain Water

在这里插入图片描述

class Solution {
    
    
public:
    int trap(vector<int>& height) {
    
    
        stack<int> S;
        int ans = 0;
        int last_height = 0;
        for(int ii = 0; ii < height.size(); ii++) {
    
    
            while(!S.empty() && height[ii] > height[S.top()]) {
    
    
                int h = min(last_height, height[ii]) - height[S.top()];
                int jj = S.top();
                S.pop();
                int kk = jj - 1;
                if(!S.empty()) kk = S.top();
                ans += h * (jj - kk);
            }
            if(S.empty()) last_height = height[ii];
            S.push(ii);
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/114271518