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;
    }
};
相关推荐
Demon--hx2 小时前
[LeetCode]100 链表-专题
算法·leetcode·链表
_深海凉_3 小时前
LeetCode热题100-LRU 缓存
算法·leetcode·缓存
liuyao_xianhui4 小时前
优选算法_岛屿的最大面积_floodfill算法_C++
java·开发语言·数据结构·c++·算法·leetcode·链表
We་ct5 小时前
LeetCode 190. 颠倒二进制位:两种解法详解
前端·算法·leetcode·typescript
禹中一只鱼5 小时前
【力扣热题100学习笔记】 - 双指针
java·笔记·学习·leetcode·贪心算法
小肝一下5 小时前
每日两道力扣,day1
算法·leetcode·职场和发展
im_AMBER5 小时前
Leetcode 151 最大正方形 | 买卖股票的最佳时机 III
数据结构·算法·leetcode·动态规划
Fly Wine5 小时前
Leetcode之简单题:在区间范围内统计奇数数目
算法·leetcode·职场和发展
x_xbx6 小时前
LeetCode:567. 字符串的排列
算法·leetcode·职场和发展