力扣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;
    }
};
相关推荐
Frostnova丶5 小时前
【算法笔记】数学知识
笔记·算法
吴可可1236 小时前
AutoCAD 2016与2014二次开发关键差异
算法
雨白7 小时前
哈希:以时间换空间的算法实战
算法
啦啦啦啦啦zzzz8 小时前
数据结构:红黑树理论
数据结构·c++·红黑树
San813_LDD9 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x138702859579 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta199810 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油10 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero11 小时前
Guava Cache Deep Dive
java·后端·算法·guava