力扣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;
    }
};
相关推荐
你怎么知道我是队长1 分钟前
C语言---循环结构
c语言·开发语言·算法
艾醒4 分钟前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
苏小瀚1 小时前
[数据结构] 排序
数据结构
纪元A梦2 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_2 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls3 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客3 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
吃着火锅x唱着歌3 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun3 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode