力扣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;
    }
};
相关推荐
一起努力啊~3 分钟前
算法刷题--哈希表
算法·面试·散列表
willingli9 分钟前
c语言经典100题 61-70题
c语言·开发语言·算法
我是小疯子6614 分钟前
深入解析C++右值引用与移动语义
java·开发语言·算法
踩坑记录15 分钟前
leetcode hot100 56.合并区间 medium
leetcode
源代码•宸24 分钟前
Golang原理剖析(Map 源码梳理)
经验分享·后端·算法·leetcode·golang·map
程序员-King.25 分钟前
day132—链表—K个一组翻转链表(LeetCode-25)
leetcode·链表·贪心算法
Narrastory29 分钟前
手把手实现蚁群算法:从数学原理到代码实践
算法
mit6.82440 分钟前
八皇后变题hash|网格dp
算法
bybitq1 小时前
LeetCode-437-路径总和3
算法
im_AMBER1 小时前
数据结构 18 【复习】广义表 | 各种内部排序 | 二叉排序树的平均查找长度 ASL
数据结构·笔记·学习·排序算法