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;
    }
};
相关推荐
hold?fish:palm3 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle4 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木4 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
啦啦啦啦啦zzzz4 小时前
算法:回溯算法
c++·算法·leetcode
小肝一下7 小时前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra
tachibana27 小时前
hot100 前 K 个高频元素(347)
java·数据结构·算法·leetcode
To_OC15 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎16 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC17 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
tachibana21 天前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode