力扣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;
    }
};
相关推荐
小园子的小菜2 分钟前
深入理解 JVM 垃圾回收:从对象判定、回收算法到经典收集器全解析
jvm·算法
hold?fish:palm5 分钟前
7 接雨水
开发语言·c++·leetcode
2601_9545267511 分钟前
【硬核长文】从卡门涡街物理方程到边缘网关温压补偿算法:工业蒸汽测控实战,深度解密靠谱的涡街流量计厂家有哪些
算法
吞下星星的少年·-·26 分钟前
牛客技能树:区间翻转
算法·滑动窗口
拂拉氏1 小时前
【知识讲解】 链式哈希表的实现与unordered_map和unordered_set的封装
数据结构·哈希算法·散列表
haolin123.1 小时前
数据结构--二叉树
数据结构
tkevinjd2 小时前
力扣148-排序链表
算法·leetcode·链表
不如语冰2 小时前
AI大模型入门-参数的传递
数据结构·人工智能·pytorch·python
qeen872 小时前
【C++】vector的模拟实现详解(二)
c++·学习·算法·迭代器·stl
流浪0012 小时前
数据结构篇(四):线性表——链表——双链表
数据结构·链表