力扣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;
    }
};
相关推荐
寒月小酒17 小时前
3.12 OJ
算法
CoovallyAIHub17 小时前
纯合成数据训练,真实图像Pose mAP达0.97:亚琛工大用YOLOv11实现风电关键点检测
深度学习·算法·计算机视觉
铭哥的编程日记17 小时前
贪心算法解决分糖果问题
算法·贪心算法
马猴烧酒.17 小时前
【JAVA算法|hot100】贪心算法类型题目详解笔记
java·开发语言·ide·笔记·算法·spring·贪心算法
xh didida17 小时前
数据结构--队列
数据结构·算法
子夜江寒17 小时前
YOLO目标检测算法简介
算法·yolo·目标检测
逆境不可逃17 小时前
LeetCode 热题 100 之 279. 完全平方数 322. 零钱兑换 139. 单词拆分 300. 最长递增子序列
java·算法·leetcode·职场和发展
美式请加冰17 小时前
位运算符的介绍和使用
数据结构·算法
tankeven17 小时前
HJ127 小红的双生串
c++·算法