zoukankan      html  css  js  c++  java
  • 42. 接雨水

    给定 n 个非负整数表示每个宽度为 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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/trapping-rain-water
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    参考 https://leetcode-cn.com/problems/trapping-rain-water/solution/trapping-rain-water-by-ikaruga/

    ///单调栈
    class Solution {
    public:
        int trap(vector<int>& height) {
            int res = 0;
            stack<int> stk;//存储下标
            int mid, l, r, h=0, w=0;
            //cout <<"size "<< height.size() << endl;
            for (int i = 0; i < height.size(); i++)
            {
                //cout << "i val "<<i << height[i] << endl;
                while (!stk.empty() && height[stk.top()] < height[i])//这里是while
                {
                    //如果将这里的while 换成if则不能正确运行
                    //因为当下一个值比栈顶元素大时 都可以接雨水 
                    //然后还要考虑栈中的其他元素是否可以接到雨水
                    mid = stk.top();
                    stk.pop();
                    if (stk.empty())break;
                    l = stk.top();
                    r = i;
                    h = min(height[l], height[r]) - height[mid];
                    w = r - l - 1;
                    res += (w * h);
                }
                stk.push(i);
            }
            return res;
        }
    };
  • 相关阅读:
    有限元方法的核心思想
    由拉格朗日函数推导守恒定律
    codeforces 1181D
    gym 102222 J
    COJ#10C
    已然逝去の夏日泳装
    NC50 E
    codeforces 1147 C
    agc 037 C
    19牛客多校第十场G
  • 原文地址:https://www.cnblogs.com/lancelee98/p/13260192.html
Copyright © 2011-2022 走看看