(leetcode学习)42. 接雨水

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

示例 1:

复制代码
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

复制代码
输入:height = [4,2,0,3,2,5]
输出:9

提示:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

通过这个题学习一下单调栈。

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> stk;
        int res = 0, n=height.size();

        for(int i=0; i<n; i++){
            while(!stk.empty() && height[ stk.top() ] <= height[i]){
                    int midh = height[stk.top()];
                    stk.pop();
                    if(stk.empty()) continue;
                    int lh = height[stk.top()], w = i - stk.top() - 1;
                    res += (min(lh, height[i]) - midh)*w;
                }
                stk.push(i);
            }
            return res;
        }
};
相关推荐
伊玛目的门徒1 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry2 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵3 小时前
【无标题】
数据结构·算法
xian_wwq4 小时前
【学习笔记】模型权重管理:Safetensors与私有化Hub(23/35)
笔记·学习
其实防守也摸鱼4 小时前
运维--学习阶段问题解答(1)(自测)
linux·运维·服务器·数据库·学习·自动化·命令模式
ctrl_v助手4 小时前
Halcon学习笔记2
人工智能·笔记·学习
Kx_Triumphs5 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
YUS云生5 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
旖-旎5 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法