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_Z2 小时前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
垆边人似月.3 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
longlongzihan3 小时前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode
kukubuzai4 小时前
二分查找系列一
数据结构·算法·leetcode
Cccp.12317 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
优质酸酸乳1 天前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光1 天前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控
yi0111 天前
LeetCode 134 加油站:从 双循环暴力 演变到 贪心
linux·算法·leetcode
yi0111 天前
DAY 14: LeetCode 394. 字符串解码|递归和栈到底怎么处理嵌套?
数据结构·笔记·python·算法·leetcode