leetcode-42. 接雨水

https://leetcode-cn.com/problems/trapping-rain-water/

单调栈应用,详细讲解 点我

class Solution {
public:
    int trap(vector& height) {
        int sum = 0,cur = 0,n = height.size();
        stack s;
        while(cur < n){
            while(!s.empty() && height[cur] > height[s.top()]){
                int t = s.top();
                s.pop();
                if(s.empty()) break;
                sum += (cur - s.top() - 1) * (min(height[s.top()],height[cur]) - height[t]);
            }
            s.push(cur++);
        }
        return sum;
    }
};

 

你可能感兴趣的:(力扣leetcode)