(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;
        }
};
相关推荐
MediaTea13 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z13 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue13 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
小郑加油13 小时前
python学习Day12:pandas安装与实际运用
开发语言·python·学习
风筝在晴天搁浅14 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
MATLAB代码顾问15 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
代码飞天15 小时前
机器学习算法和函数整理——助力快速查阅
人工智能·算法·机器学习
jiushiapwojdap15 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
MegaDataFlowers15 小时前
英语六级我还在背单词:Unit 1(Lesson 2)
学习
笨笨饿15 小时前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发