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

相关推荐
夏日听雨眠3 分钟前
数据结构(栈和队列)
数据结构
Aaswk9 分钟前
Java Lambda 表达式与流处理
java·开发语言·python
万邦科技Lafite28 分钟前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
王老师青少年编程1 小时前
csp信奥赛C++高频考点专项训练之字符串 --【子串查找】:[NOIP 2009 提高组] 潜伏者
c++·字符串·csp·高频考点·信奥赛·子串查找·潜伏者
Cyber4K1 小时前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php
梦梦代码精1 小时前
BuildingAI 上部署自定义工作流智能体:5 个实用技巧
大数据·人工智能·算法·开源软件
初願致夕霞1 小时前
基于系统调用的Linux网络编程——UDP与TCP
linux·网络·c++·tcp/ip·udp
Le_ee2 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php
Zephyr_02 小时前
Leedcode算法题
java·算法