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;
    }
};
相关推荐
带多刺的玫瑰3 小时前
Leecode#26刷题之删除有序数组中的重复项
数据结构·算法·leetcode
wabs6666 小时前
关于二叉树【429.N叉树的层序遍历的思考】
数据结构·c++·算法·leetcode·二叉树
不会就选b7 小时前
算法日常・每日刷题--<贪心>6
数据结构·算法·leetcode
青山木7 小时前
Hot 100 --- 跳跃游戏 II
java·数据结构·算法·leetcode·贪心算法
Tisfy7 小时前
LeetCode 3870.统计范围内的逗号:模拟 或 一步计算
数学·算法·leetcode·题解·模拟·遍历
木井巳8 小时前
【BFS/DFS 解决 FloodFill 算法】衣橱整理
java·算法·leetcode·深度优先·广度优先·宽度优先
shehuiyuelaiyuehao10 小时前
算法40,模拟运算,替换所有的问号
数据结构·算法·leetcode
橘子汽水16811 小时前
Leetcode 128,49最长连续序列,字母异位词分组
java·算法·leetcode
圣保罗的大教堂11 小时前
leetcode 1140. 石子游戏 II 中等
leetcode