(leetcode学习)42. 接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例 1:

复制代码
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

复制代码
输入:height = [4,2,0,3,2,5]
输出:9

提示:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

通过这个题学习一下单调栈。

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> stk;
        int res = 0, n=height.size();

        for(int i=0; i<n; i++){
            while(!stk.empty() && height[ stk.top() ] <= height[i]){
                    int midh = height[stk.top()];
                    stk.pop();
                    if(stk.empty()) continue;
                    int lh = height[stk.top()], w = i - stk.top() - 1;
                    res += (min(lh, height[i]) - midh)*w;
                }
                stk.push(i);
            }
            return res;
        }
};
相关推荐
.道阻且长.8 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC10 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore12 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR13 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
圆奋奋14 小时前
FreeRTOS学习(三)- 任务调度模块
学习·开源·freertos
吃着火锅x唱着歌14 小时前
Effective C++ 学习笔记 条款40 明智而审慎地使用多重继承
c++·笔记·学习
Tisfy14 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
xian_wwq15 小时前
【学习笔记】Prompt Engineering 没死,只是它不再够用了-2/16
笔记·学习·prompt
lucas_AI15 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法