当前位置: 首页 > news >正文

代码随想录训练营day49|单调栈part2

接雨水

力扣题目链接

class Solution {
public:int trap(vector<int>& height) {int h = 0;int result = 0;stack<int> st;//存index// st.push(0);for(int i = 0; i < height.size(); i++){if(!st.empty() && height[st.top()] <= height[i]){while(!st.empty() && height[st.top()] < height[i]){h = height[st.top()];st.pop();if(!st.empty()){int w = i-st.top()-1;int h2 = min(height[st.top()], height[i])-h;result += h2 * w;}} }st.push(i);}return result;}
};

柱状图中最大的矩形

力扣题目链接

class Solution {
public:int largestRectangleArea(vector<int>& heights) {int result = 0;unordered_map<int, int> umap;stack<int> st;// 栈内元素递增for(int i = 0; i < heights.size(); i++){if(st.empty() || heights[st.top()] < heights[i]){st.push(i);}else{int j;// 遇到更小的元素时弹出,将入栈元素的index变为出栈的元素的,这里用覆盖heights来实现while(!st.empty() && heights[st.top()] >= heights[i]){j = st.top();// 判断局部矩阵result = max(result, (i-j) * heights[j]);heights[j] = heights[i];st.pop();}st.push(j);}}// 将递增栈的元素弹出,栈内元素满足到heights.size()处为矩形while(!st.empty()){int j = heights.size();result = max(result, heights[st.top()] * (j - st.top()));st.pop();}return result;}
};

http://www.mrgr.cn/news/11551.html

相关文章:

  • Python——类和对象、继承和组合
  • 数据结构——链式二叉树的实现与分治编程思维(c语言实现)
  • C语言指针详解(2)
  • 操作系统读写锁
  • 4820道西医综合真题西医真题ACCESS\EXCEL数据库
  • 计算机毕业设计选题推荐-地震数据分析与预测-Python爬虫可视化
  • springboot故障分析FailureAnalyzer
  • 深入解析Smarty SSTI 利用
  • 普通项目解决跨域问题,springSecurity解决跨域问题以及文件配置
  • 进程的创建,结束,回收基础API
  • Spring Boot : ORM 框架 JPA 与连接池 Hikari
  • 大模型学习必备指南:深入解析技术原理与应用,从入门到精通一应俱全
  • 软考攻略/超详细/系统集成项目管理工程师/基础知识分享04
  • Kafka事件(消息、数据、日志)的存储
  • 4. kafka消息监控客户端工具
  • S3协议分片上传(minio)
  • kubebuiler开发operator理论术语
  • Postman【使用总结】--SpringBoot的Controller规范【重修】
  • C#入门(16)for循环
  • 使用AWS的EC2服务如何降低成本