LeetCode 力扣 热题 100道(二十一)接雨水(C++)

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

代码如下所示:

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

        int left = 0, right = n - 1;
        int left_max = 0, right_max = 0;
        int water = 0;

        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] >= left_max) {
                    left_max = height[left]; // 更新左侧最大高度
                } else {
                    water += left_max - height[left]; // 累加雨水
                }
                ++left; // 左指针右移
            } else {
                if (height[right] >= right_max) {
                    right_max = height[right]; // 更新右侧最大高度
                } else {
                    water += right_max - height[right]; // 累加雨水
                }
                --right; // 右指针左移
            }
        }

        return water;
    }
};

利用两个指针分别从数组的两端向中间遍历。

同时维护两个变量:

left_max:从左侧当前最大高度。

right_max:从右侧当前最大高度。

计算能接的雨水:

如果 height[left] 小于等于 height[right],则 left 所在位置的最大雨水由 left_max - height[left] 决定,更新左指针。

如果 height[right] 小于 height[left],则 right 所在位置的最大雨水由 right_max - height[right] 决定,更新右指针。

继续移动指针,直到 left == right

相关推荐
sitellla1 分钟前
Pydub:用 Python 处理音频,不写废话
开发语言·python·其他·音视频
happymaker06268 分钟前
LeetCodeHot100——155.最小栈
算法
xingyuzhisuan9 分钟前
缓存命中率提升方案:从 30% 优化至 82% 全流程优化记录
java·开发语言·缓存·ai
郑洁文15 分钟前
基于Python的恶意流量监测系统的设计与实现
开发语言·python
AI玫瑰助手17 分钟前
Python流程控制:for循环与range函数的搭配使用
开发语言·python·信息可视化
洛水水18 分钟前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
anew___20 分钟前
2026年Python爬虫技术完全指南:从入门到实战
开发语言·爬虫·python
Penfy_Z22 分钟前
【Python LLM 调用踩坑】Connection error 终极解决方案!npm 代理导致阿里云通义千问接口连接失败
开发语言·python·npm
星辰徐哥22 分钟前
Python AI基础:Python面向对象编程
开发语言·人工智能·python
Coder-magician22 分钟前
《代码随想录》刷题打卡day15:二叉树part05
数据结构·c++·算法