代码随想录算法【Day47】

Day49

42. 接雨水

思路

这道题利用单调栈进行横向求解。对于每一个元素,找到它右边第一个比它大的元素和左边第一个比它大(或者与它相等的元素,当然这种情况可以忽略),最后计算雨水的存储量:((左右两边的高度差)减去(中间元素的高度))乘上中间元素的宽度。为什么要乘中间元素的宽度?因为中间元素可能不止一个。

代码

复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        // if(height.size() <= 2) return 0;   //加不加都可以,最好加上
        stack<int> st;
        st.push(0);
        int sum;
        for(int i = 1; i < height.size(); i++){ //直接从第二个元素开始遍历
            if(height[i] < height[st.top()]) st.push(i);
            else if(height[i] == height[st.top()]){
                st.pop();
                st.push(i);
            }
            else{
                while(!st.empty() && height[i] > height[st.top()]){
                    int mid = st.top();
                    st.pop();
                    if(!st.empty()){   //如果这里是true,会发生什么?
                        int h = min(height[st.top()], height[i]) - height[mid];
                        int w = i - st.top() - 1;
                        sum += h * w;
                    }
                }
                st.push(i);
            }
        }
        return sum;
    }
};

等等

相关推荐
小白菜又菜6 分钟前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见4046 分钟前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
多恩Stone10 分钟前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
踢足球092923 分钟前
寒假打卡:2026-2-23
数据结构·算法
田里的水稻1 小时前
FA_建图和定位(ML)-超宽带(UWB)定位
人工智能·算法·数学建模·机器人·自动驾驶
Navigator_Z1 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
郝学胜-神的一滴1 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
摸鱼仙人~1 小时前
算法题避坑指南:数组/循环范围的 `+1` 到底什么时候加?
算法
liliangcsdn1 小时前
基于似然比的显著图可解释性方法的探索
人工智能·算法·机器学习
骇城迷影1 小时前
代码随想录:二叉树篇(中)
数据结构·c++·算法·leetcode