leetcode 42 接雨水(单调栈)

42. 接雨水

难度困难1369

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

leetcode 42 接雨水(单调栈)_第1张图片

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

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

解题思路:

我们希望找到每根柱子从左往右所做的贡献,很显然,当我们在第i根柱子向右拓展找到第1根比第i根高的柱子,然后我们答案更新可以用(j-i-1)*i - block. block就是j和i之间的柱子的高度,因为它们是泡在水里的所以它们要被减掉。

假如我们的第i根柱子往右延拓找不到比它高的柱子呢?这时候我们想找的是从右往左看以i根柱子为第1根比它高的柱子的最远的柱子。以下为例:

leetcode 42 接雨水(单调栈)_第2张图片

class Solution {
public:
    int trap(vector& height) {
        vector pref,post;
        int n = height.size();
        pref.assign(n+1,-1);
        post=pref;
        stack sta;
        unordered_map mm;
        for(int i =0;i= height[sta.top()]){
                pref[sta.top()] = i;
                sta.pop();
            }
            sta.push(i);
        }
        sta=stack();
        for(int i=n-1;i>=0;i--){
            while(sta.size() && height[i]>=height[sta.top()]){
                mm[i]=sta.top();
                post[sta.top()] = i;
                sta.pop();
            }
            sta.push(i);
        }
        
        int ans = 0;
        int poi = 0;
        while(poi

 

你可能感兴趣的:(leetcode,单调栈)