代码随想录训练营第54天|单调栈+双指针

42. 接雨水

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        int n=height.size(), sum=0;
        vector<int> max_left=height, max_right=height;
        for(int i=1; i<n; i++){
            max_left[i]=max(max_left[i-1],max_left[i]);
        }
        for(int i=n-2; i>=0; i--){
            max_right[i]=max(max_right[i],max_right[i+1]);
        }
        for(int i=0; i<n; i++){
            int cur=min(max_left[i],max_right[i])-height[i];
            if(cur>0)
                sum+=cur;
        }
        return sum;
    }
};

双指针解法:

max_lefti:第i个元素以左(包含第i个),所有元素的最大值

max_righti:第i个元素以右(包含第i个),所有元素的最大值

按列统计雨水容量,每列可装的雨水高度:min(max_lefti,max_righti)-heighti

84. 柱状图中最大的矩形

cpp 复制代码
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n=heights.size(),max_area=INT_MIN;
        stack<int> st;
        vector<int> left(n,-1);
        vector<int> right(n,n);
        for(int i=0; i<n; i++){
            while(!st.empty()&&heights[i]<heights[st.top()]){
                right[st.top()]=i;
                st.pop();
            }
            st.push(i);
        }
        st=stack<int>();
        for(int i=n-1; i>=0; i--){
            while(!st.empty()&&heights[i]<heights[st.top()]){
                left[st.top()]=i;
                st.pop();
            }
            st.push(i);
        }
        for(int i=0; i<n; i++){
            int cur=heights[i]*(right[i]-left[i]+1-2);
            max_area=max(max_area,cur);
        }
        return max_area;

    }
};

尝试所有可能的中心高度,累计最大值。选定heightsi作为中心,向两边膨胀得到最大面积,当遇到第一个比它小的元素时,则不可继续膨胀(否则会以更小的这个元素为中心,而不是heightsi),也就是问题转化为求【下一个更小元素】的问题,参考上一篇博客,经典的单调栈解法。

从前往后扫,得到右侧第一个更小;

从后往前扫,得到左侧第一个更小。

注意,left和right的元素时取不到的,所以计算宽度时要减2。

相关推荐
console.log('npc')2 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
橘子133 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘14 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴18 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David18 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
Pniubi21 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK21 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司1 天前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
阿庆_AI研发工程师1 天前
Stanford CS336 Lecture 10:大语言模型推理与性能优化
算法
用户7341681035481 天前
基于MindSpore的深度残差收缩网络程序
算法