力扣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;
    }
};
相关推荐
Pniubi1 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊12 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考12 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊13 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~16 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯18 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好18 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘19 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程20 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊20 小时前
LeetCode3061~3080题目解析
java·leetcode