力扣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;
    }
};
相关推荐
Gigavision1 分钟前
MMPD数据集 最新Mamba算法 源码+数据集 下载方式
算法
Xの哲學10 分钟前
Linux UPnP技术深度解析: 从设计哲学到实现细节
linux·服务器·网络·算法·边缘计算
歌_顿10 分钟前
GPT 系列学习总结(1-3)
算法
业精于勤的牙13 分钟前
最长特殊序列(三)
算法
柏木乃一14 分钟前
进程(6)进程切换,Linux中的进程组织,Linux进程调度算法
linux·服务器·c++·算法·架构·操作系统
皮卡蛋炒饭.14 分钟前
前缀和与差分
算法
0x7F7F7F7F32 分钟前
算法竞赛数学知识大全
算法
业精于勤的牙1 小时前
最长特殊序列(二)
java·开发语言·算法
yong99901 小时前
C#实现OPC客户端与S7-1200 PLC的通信
开发语言·网络·算法·c#
yaoh.wang1 小时前
力扣(LeetCode) 111: 二叉树的最小深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·深度优先