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;
    }
};
相关推荐
Shaoshing5 小时前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展
圣保罗的大教堂7 小时前
leetcode 3884. 双端字符匹配 简单
leetcode
Shaoshing11 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode
Navigator_Z14 小时前
LeetCode //C - 1331. Rank Transform of an Array
c语言·算法·leetcode
Tisfy14 小时前
LeetCode 1202.交换字符串中的元素:分组排序(连通图)
算法·leetcode·字符串·bfs·题解·排序·连通图
小白的高手之路1 天前
【LeetCode 热题 100】206. 反转链表|链表、迭代、递归(Python)
笔记·python·算法·leetcode·链表·职场和发展·力扣
16月6日-晴1 天前
122. 买卖股票的最佳时机 II【贪心】
算法·leetcode
小白的高手之路1 天前
【【LeetCode 热题 100】160. 相交链表|链表、哈希表、双指针(Python)
python·算法·leetcode·链表·力扣·散列表
灯澜忆梦1 天前
拓扑排序(Kahn BFS)| LeetCode 210 课程表 II
算法·leetcode·排序算法·宽度优先
Nuanyt2 天前
LeetCode Hot 100 贪心算法专题 121 / 55 / 45 / 763 (Java)
java·算法·leetcode·贪心算法·dp