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;
    }
};
相关推荐
海清河晏11128 分钟前
加油站问题
数据结构·算法·leetcode
Nuanyt2 小时前
LeetCode Hot 100 · 双指针 3 题 Java
java·笔记·算法·leetcode·双指针
文丑颜不良啊3 小时前
LeetCode851~875题目解析
java·leetcode
Navigator_Z3 小时前
LeetCode //C - 1304. Find N Unique Integers Sum up to Zero
c语言·算法·leetcode
?abc!15 小时前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
hold?fish:palm18 小时前
40 二叉树的直径
c++·leetcode
guo_wen_qiang19 小时前
二叉树的层序遍历-使用双端队列Deque
算法·leetcode·1024程序员节
爱读书的小胖19 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
Navigator_Z21 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
凯瑟琳.奥古斯特21 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展