leetcode-----42. 接雨水

代码

class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> stk;
        int ans = 0;
        for (int i = 0; i < height.size(); ++i) {
            int last = 0;
            while (stk.size() && height[stk.top()] <= height[i]) {
                ans += (height[stk.top()] - last) * (i - stk.top() - 1);
                last = height[stk.top()];
                stk.pop();
            }
            if (stk.size()) ans += (i - stk.top() - 1) * (height[i] - last);
            stk.push(i);
        }
        return ans;
    }
};
posted @ 2020-07-06 16:26  景云ⁿ  阅读(57)  评论(0编辑  收藏  举报