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;
    }
};
相关推荐
文丑颜不良啊2 分钟前
LeetCode2761~2780题目解析
java·leetcode
文丑颜不良啊3 小时前
LeetCode2841~2860题目解析
java·leetcode
文丑颜不良啊5 小时前
LeetCode2921~2940题目解析
java·leetcode
文丑颜不良啊7 小时前
LeetCode2901~2920题目解析
java·leetcode
文丑颜不良啊9 小时前
LeetCode2861~2880题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2821~2840题目解析
java·leetcode
Pniubi1 天前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
文丑颜不良啊1 天前
LeetCode2741~2760题目解析
java·leetcode
俊俊几年的1 天前
动态规划(Dynamic Programming)详解:从入门到 LeetCode Hot 100
linux·c++·算法·leetcode·嵌入式·动态规划·c
希望我万事顺遂2 天前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode