Leetcode 42.接雨水

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

单调栈

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> stk;
        int res = 0;
        for(int i = 0; i < height.size(); i ++ ) {
            int last = 0;
            while(stk.size() && height[stk.top()] <= height[i]) {
                res += (height[stk.top()] - last) * (i - stk.top() - 1);
                last = height[stk.top()];
                stk.pop();
            }
            if(stk.size()) res += (height[i] - last) * (i - stk.top() - 1);
            stk.push(i);
        }
        return res;
    }
};

双指针

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0;
        int l = 0, r = height.size() - 1;
        int lmax = 0, rmax = 0;
        while(l < r) {
            lmax = max(lmax, height[l]);
            rmax = max(rmax, height[r]);
            if(height[l] < height[r]) {
                res += lmax - height[l];
                l ++;
            } else {
                res += rmax - height[r];
                r --;
            }
        }
        return res;
    }
};
相关推荐
不会就选b13 分钟前
算法日常・每日刷题--<动态规划>26
算法·动态规划
荆棘鸟智能26 分钟前
虫情测报灯图像识别算法实践:小目标检测、粘连计数与飞虱细粒度分类
算法·目标检测·分类
学电子她就能回来吗36 分钟前
LeetCode Hot 100|滑动窗口专题零基础学习笔记
笔记·学习·leetcode
爱读书的小胖1 小时前
LeetCode 27. 移除元素(C)解题分析
数据结构·算法
科技小E1 小时前
敏感数据不敢上云训练?本地大模型推理服务器DLTM私有化部署,让训练全程留在企业内网
大数据·算法·自动化
小草cys1 小时前
用 GPT 直接生成可编辑 PPTX 的实操记录,artifact-tool是OpenAICodex环境专用
gpt·算法·pptx
爱读书的小胖1 小时前
Codewars: A Brave New Wordle(C)解题分析
c语言·数据结构·算法
Escalating_xu1 小时前
【数据结构】顺序表的应用:动态通讯录项目与双指针经典算法
c语言·数据结构·算法
其实防守也摸鱼1 小时前
CTF Web 6 题全解 Writeup
linux·sql·学习·算法·安全·ctf·xss
宇明一不急1 小时前
string和byte的相互转换
算法