(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;
        }
};
相关推荐
星夜夏空9912 小时前
C++学习(2) —— 类与对象基础
开发语言·c++·学习
-To be number.wan12 小时前
数据库系统 | 数据库安全与完整性
数据库·学习
wabs66612 小时前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月13 小时前
54.螺旋矩阵
java·算法·leetcode·矩阵
czysoft13 小时前
se被限速
科技·学习·it·技术·魔法·先进·领先
Robot_Nav13 小时前
MPPI 局部规划器实验设计讲解
人工智能·算法·mppi
子不语18013 小时前
从0开始学习S7-1200+ET200SP(3)——两台S7-1200通过TCP连接
网络协议·学习·tcp/ip
mingo_敏14 小时前
Mean-Teacher 均值教师自训练框架详解
算法·均值算法
llllliznc14 小时前
LLM 学习笔记 Day 5:Agent 核心组件——Planner、Memory 与 Reflection
笔记·学习
星空露珠14 小时前
迷你世界UGc3.0脚本Wiki[剧情动画模块管理接口 Timeline]
开发语言·数据结构·算法·游戏·lua