力扣42. 接雨水

双指针法

  • 思路:
    • 将数组前后设置为 left、right 指针,相互靠近;
    • 在逼近的过程中记录两端最大的值 leftMax、rightMax,作为容器的左右边界;
    • 更新指针规则:
      • 如果数组左边的值比右边的小,则更新 left 指针,同时累计当前组成的容器的容量;(该容器在更新 leftMax 时闭合)
      • 反之,则更新 right 指针,同理累计其组成容器的容量;
cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        int capacity = 0;
        int left = 0;
        int right = height.size() - 1;
        int leftMax = 0;
        int rightMax = 0;

        while (left < right) {
            leftMax = std::max(leftMax, height[left]);
            rightMax = std::max(rightMax, height[right]);
            if (height[left] < height[right]) {
                capacity += (leftMax - height[left]);
                ++left;
            } else {
                capacity += (rightMax - height[right]);
                --right;
            }
        }

        return capacity;
    }
};
相关推荐
持续学习的程序员+1几秒前
强化学习Q-chunking算法
算法
Polaris北17 分钟前
第二十七天打卡
开发语言·c++·算法
风吹乱了我的头发~41 分钟前
Day30:2026年2月20日打卡
算法
blackicexs1 小时前
第五周第五天
算法
不吃橘子的橘猫1 小时前
《集成电路设计》复习资料2(设计基础与方法)
学习·算法·fpga开发·集成电路·仿真·半导体
halen3331 小时前
How Masters Tool Fixed My Digital Disaster
算法·均值算法·推荐算法
重生之后端学习2 小时前
78. 子集
java·数据结构·算法·职场和发展·深度优先
摸鱼仙人~2 小时前
0-1背包与完全背包:遍历顺序背后的秘密
人工智能·算法
juleskk2 小时前
2.15 复试训练
开发语言·c++·算法
kronos.荒2 小时前
滑动窗口+哈希表:最小覆盖子串
数据结构·python·散列表