42. 接雨水

文章目录

题意

题目链接

思路

单调栈

代码

C++ 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> s;
        int ans = 0;
        for (int i = 0; i < height.size(); i++) {
            const int x = height[i];
            while (!s.empty() && height[s.top()] <= x) {
                const int h = height[s.top()];
                s.pop();
                if (s.empty())
                    break;
                int left = s.top();
                int dh = min(height[left], height[i]) - h;
                ans += dh * (i - left - 1);
            }
            s.push(i);
        }
        
        
        return ans;
    }
};
相关推荐
Navigator_Z9 小时前
LeetCode //C - 1192. Critical Connections in a Network
c语言·算法·leetcode
rannn_11110 小时前
【力扣hot100】链表专题下|138、148、23、146
java·算法·leetcode·链表·开发
hanlin0311 小时前
刷题笔记:力扣第189题-轮转数组
笔记·算法·leetcode
琥珀色糖11 小时前
leetcode hot100题(持续更新)移动零(双指针)
算法·leetcode·职场和发展·双指针·移动零
hanlin0312 小时前
动态规划专练:力扣第718、1143题
算法·leetcode·动态规划
hanlin0316 小时前
动态规划专练:力扣第1035、392题
算法·leetcode·动态规划
evans在进步17 小时前
LeetCode 34:在排序数组中查找元素的首尾位置——Java 两次二分查找详解
java·python·leetcode
杨航 AI19 小时前
** AI 面试算法 50 题清单**,不是单纯的 LeetCode 题号列表,而是按照“**考察概率 × 面试价值 × 你当前准备方向**”排序
算法·leetcode·面试
.道阻且长.1 天前
5.LeetCode算法习题讲解--双指针--有效三角形的个数
算法·leetcode·职场和发展
xin_nai1 天前
LeetCode热题100(Java)(7)链表(下)
java·leetcode·链表