力扣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;
    }
};
相关推荐
2301_8194143023 分钟前
C++与区块链智能合约
开发语言·c++·算法
Zaly.29 分钟前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
不想看见40430 分钟前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
做怪小疯子44 分钟前
蚂蚁暑期 319 笔试
算法·职场和发展
计算机安禾1 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
啊哦呃咦唔鱼1 小时前
LeetCode hot100-73 矩阵置零
算法
阿贵---1 小时前
C++构建缓存加速
开发语言·c++·算法
Queenie_Charlie1 小时前
最长回文子串 V2(Manacher算法)
c++·算法·manacher算法
Evand J2 小时前
【MATLAB复现RRT(快速随机树)算法】用于二维平面上的无人车路径规划与避障,含性能分析与可视化
算法·matlab·平面·无人车·rrt·避障
一招定胜负2 小时前
机器学习+深度学习经典算法面试复习指南
深度学习·算法·机器学习