力扣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;
    }
};
相关推荐
洛水水7 分钟前
【力扣100题】33.验证二叉搜索树
算法·leetcode·职场和发展
SimpleLearingAI20 分钟前
聚类算法详解
算法·数据挖掘·聚类
刀法如飞1 小时前
Go 字符串查找的 20 种实现方式,用不同思路解决问题
算法·面试·程序员
Dlrb12113 小时前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora3 小时前
Python 算法基础篇之集合
python·算法
平行侠3 小时前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
阿旭超级学得完4 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
li星野4 小时前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法
jerryinwuhan5 小时前
hello算法,简单讲(1)
算法·排序算法
y = xⁿ5 小时前
20天速通LeetCodeday15:BFS广度优先搜索
算法·宽度优先