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。

相关推荐
apcipot_rain2 小时前
C++转Java日记(04)
java·开发语言·c++
NEFU_Jyj3 小时前
牛客周赛R168
算法
云和数据.ChenGuang4 小时前
LangGraph 异步 Node 的设计与写法实践
开发语言·人工智能·python·机器学习·php
WL学习笔记5 小时前
vector模拟实现
c++
蜗牛一步步往上爬7 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
张张123y9 小时前
DSH 插件调试避坑:client.js 设置面板、热重载与高频报错排查表
开发语言·javascript·人工智能·开源·ecmascript·后端开发·ai agent
likexuec9 小时前
数据结构(2)
数据结构
文丑颜不良啊10 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z10 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode