力扣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;
    }
};
相关推荐
铭哥的编程日记几秒前
小企鹅装石头(栈模拟题)
算法
汉堡go2 分钟前
SLAM数学基础1
人工智能·算法·机器学习
汉克老师3 分钟前
GESP 四级C++考试2025年3月第二部分判断题(1-10题)
数据结构·c++·排序算法·指针·结构体·gesp4级·gesp四级
qzhqbb3 分钟前
不可检测水印
人工智能·算法
快敲啊死鬼4 分钟前
机试day5
算法·华为od·华为
8Qi86 分钟前
LeetCode热题100--189
c语言·数据结构·c++·算法·leetcode
灰色小旋风6 分钟前
力扣第八题C++ 字符串转换整数
c++·算法·leetcode
进击的雷神8 分钟前
请求频率限制、嵌套数据结构、多目录聚合、地址字段重构——K展爬虫四大技术难关攻克纪实
数据结构·爬虫·python·重构
@––––––8 分钟前
力扣hot100—系列9—图论
算法·leetcode·图论
pp起床10 分钟前
图论 | part01
算法·深度优先·图论