力扣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 分钟前
csp信奥赛C++之摩尔投票算法详解
数据结构·c++·算法·题解·csp·信奥赛·摩尔投票算法
Purple Coder10 分钟前
基于GNN的超导材料生长方法研究算法的实现-1
算法
tod11312 分钟前
C++ 核心知识点全解析(六)
c++·算法·面试经验
m0_5312371712 分钟前
C语言-编程实例
c语言·开发语言·数据结构
紫陌涵光14 分钟前
701. 二叉搜索树中的插入操作
算法·leetcode
tankeven16 分钟前
HJ100 等差数列
c++·算法
ADDDDDD_Trouvaille17 分钟前
2026.2.22——OJ98-100题
c++·算法
闻缺陷则喜何志丹21 分钟前
【差分数组】P9166 [省选联考 2023] 火车站|普及+
数据结构·c++·洛谷·差分数组
tankeven22 分钟前
HJ99 自守数
c++·算法
一只理智恩27 分钟前
基于 CesiumJS + React + Go 实现三维无人机编队实时巡航可视化系统
前端·人工智能·算法·golang·无人机