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。

相关推荐
geovindu36 分钟前
python:Lasso
开发语言·后端·python·算法
多加点辣也没关系1 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
3095566661 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
AAA修煤气灶刘哥1 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
csdn_aspnet2 小时前
C++ 求给定点集的简单闭合路径(Find Simple Closed Path for a given set of points)
c++
艾莉丝努力练剑2 小时前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构
Severus_black2 小时前
【C++初阶】模板进阶
c语言·c++·学习
利威尔xu2 小时前
2026-11-19-Go反射为什么慢面试
开发语言·面试·golang
AAA修煤气灶刘哥2 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
山楂树の2 小时前
Python 函数:参数、作用域、Lambda 与类型注解
开发语言·python