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;
    }
};
相关推荐
We་ct2 小时前
LeetCode 39. 组合总和:DFS回溯解法详解
前端·算法·leetcode·typescript·深度优先·个人开发·回溯
Eward-an7 小时前
LeetCode 1980 题通关指南|3种解法拆解“找唯一未出现二进制串”问题,附Python最优解实现
python·算法·leetcode
程序员酥皮蛋8 小时前
hot 100 第四十题 40.二叉树的层序遍历
数据结构·算法·leetcode
We་ct10 小时前
LeetCode 77. 组合:DFS回溯+剪枝,高效求解组合问题
开发语言·前端·算法·leetcode·typescript·深度优先·剪枝
努力学算法的蒟蒻10 小时前
day105(3.6)——leetcode面试经典150
算法·leetcode·面试
im_AMBER10 小时前
Leetcode 136 最小栈 | 逆波兰表达式求值
数据结构·学习·算法·leetcode·
识君啊10 小时前
Java字符串算法核心攻略
java·数据结构·算法·leetcode·字符串·
郝学胜-神的一滴10 小时前
力扣86题分隔链表:双链表拆解合并法详解
开发语言·数据结构·算法·leetcode·链表·职场和发展
快快起来写代码10 小时前
【leetcode】容器中水的容量最小/大面积
算法·leetcode·职场和发展