当前位置:网站首页>leetcode 84.柱状图中最大的矩形 单调栈应用
leetcode 84.柱状图中最大的矩形 单调栈应用
2022-08-10 19:06:00 【Alkali!】
题目描述
思路
首先,要想找到第 i i i 位置最大面积是什么?(这是本题的关键点,要知道怎么去计算面积!)
是以i 为中心,向左找第一个小于 h e i g h t s [ i ] heights[i] heights[i] 的位置 l e f t i left_i lefti;向右找第一个小于于 h e i g h t s [ i ] heights[i] heights[i] 的位置 r i g h t i right_i righti,即最大面积为 h e i g h t s [ i ] ∗ ( r i g h t i − l e f t i − 1 ) heights[i] * (right_i - left_i -1) heights[i]∗(righti−lefti−1),如下图所示:
那么如何找到每个位置 i i i的 l e f t i left_i lefti和 r i g h t i right_i righti呢?
这里我们利用单调栈的思想就行,可以实现 O ( n ) O(n) O(n)的复杂度。
直接看代码
代码
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
vector<int> left,right;
stack<pair<int,int>> s;
//求lefti
for(int i=0;i<heights.size();i++)
{
while(!s.empty()&&s.top().second>=heights[i])
s.pop();
if(s.empty())
left.push_back(-1); //如果找不到左边第一个比它小的,说明它是最小的,那直接拉到-1
else
left.push_back(s.top().first);
s.push({
i,heights[i]});
}
while(!s.empty()) s.pop(); //清空栈
//求righti
for(int i=heights.size()-1;i>=0;i--)
{
while(!s.empty()&&s.top().second>=heights[i])
s.pop();
if(s.empty())
right.push_back(heights.size());//如果找不到右边第一个比它小的,说明它是最小的,那直接拉到n
else
right.push_back(s.top().first);
s.push({
i,heights[i]});
}
reverse(right.begin(),right.end()); //答案得逆置一下
int res=0;
for(int i=0;i<heights.size();i++)
res=max(res,(right[i]-left[i]-1)*heights[i]); //求可能的最大面积
return res;
}
};
边栏推荐
- (十二) findContours函数的hierarchy详解
- Optimizing Bloom Filter: Challenges, Solutions, and Comparisons论文总结
- IIC通信协议总结[通俗易懂]
- [Teach you how to do mini-games] How to lay out the hands of Dou Dizhu?See what the UP master of the 250,000 fan game area has to say
- 西安凯新(CAS:2408831-65-0)Biotin-PEG4-Acrylamide 特性
- 常见端口及服务
- 转铁蛋白修饰长春新碱-粉防己碱脂质体|转铁蛋白修饰共载紫杉醇和金雀异黄素脂质体(试剂)
- 网站架构探测&chrome插件用于信息收集
- 端口探测详解
- 大家要的Biotin-PEG3-Br/acid/NHS ester/alcohol/amine合集分享
猜你喜欢
转铁蛋白修饰长春新碱-粉防己碱脂质体|转铁蛋白修饰共载紫杉醇和金雀异黄素脂质体(试剂)
- [email protected])纳米酶"/>
血红素-金纳米颗粒(Heme-AuNP)复合纳米酶|金纳米颗粒核多孔空心碳纳米球壳([email protected])纳米酶
Modern Privacy-Preserving Record Linkage Techniques: An Overview论文总结
子域名收集&Google搜索引擎语法
铱钌合金/氧化铱仿生纳米酶|钯纳米酶|GMP-Pd纳米酶|金钯复合纳米酶|三元金属Pd-M-Ir纳米酶|中空金铂合金纳米笼核-多空二氧化硅壳纳米酶
whois information collection & corporate filing information
2022杭电多校七 Black Magic (签到)
【Knowledge Sharing】What is SEI in the field of audio and video development?
WCF and TCP message communication practice, c # 】 【 realize group chat function
servlet映射路径匹配解析
随机推荐
电脑为什么会蓝屏的原因
工业基础类—利用xBIM提取IFC几何数据
UnitTest中的Path must be within the project 问题
Optimizing Bloom Filter: Challenges, Solutions, and Comparisons论文总结
转铁蛋白修饰蛇床子素长循环脂质体/负载三七皂苷R1的PEG-PLGA纳米粒([email protected] NPs)
(十二) findContours函数的hierarchy详解
whois信息收集&企业备案信息
网络虚拟化
LeetCode·26.删除有序数组中的重复项·双指针
电脑重装系统Win11格式化硬盘的详细方法
【CNN】刷SOTA的trick
opengrok搭建[通俗易懂]
servlet映射路径匹配解析
[TAPL] 概念笔记
800. 数组元素的目标和(双指针)
mysql 中大小写问题
代理模式的使用总结
Redis 持久化机制
About npm/cnpm/npx/pnpm and yarn
【无标题】基于Huffman和LZ77的GZIP压缩