力扣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;
    }
};
相关推荐
穿条秋裤到处跑16 小时前
每日一道leetcode(2026.04.07):模拟行走机器人 II
leetcode·机器人
sheeta199816 小时前
LeetCode 每日一题笔记 日期:2026.04.07 题目:2069.模拟行走机器人二
笔记·leetcode·机器人
im_AMBER16 小时前
Leetcode 153 课程表 | 腐烂的橘子
开发语言·算法·leetcode·深度优先·图搜索
paeamecium16 小时前
【PAT甲级真题】- Reversing Linked List (25)
数据结构·c++·算法·pat
田梓燊16 小时前
leetcode 73
算法·leetcode·职场和发展
ZPC821016 小时前
相机接入ROS2 流程及问题排查
人工智能·算法·机器人
2501_9403152616 小时前
【无标题】两个相同字符串中不同字符的个数
算法·哈希算法·散列表
6Hzlia16 小时前
【Hot 100 刷题计划】 LeetCode 54. 螺旋矩阵 | C++ 模拟法题解
c++·leetcode·矩阵
算法鑫探16 小时前
显示器插座最短连线算法(蓝桥杯十六届C组编程题第二题)
c语言·数据结构·算法·排序算法·新人首发
akarinnnn16 小时前
【DAY15】:深⼊理解指针(6)
算法