算法修炼Day60|● 84.柱状图中最大的矩形

LeetCode:84.柱状图中最大的矩形

84. 柱状图中最大的矩形 - 力扣(LeetCode)

1.思路

双指针思路,以当前数组为中心,借助两个数组存放当前数柱左右两侧小于当前数柱高度的索引,进行h*w的计算。注意首尾节点的左侧索引和右侧索引需要单独声名为0.

单调栈,在原数组的基础上定义一个新的数组,对其进行首尾节点的扩容。思路延续收集雨水。

2.代码实现
java 复制代码
class Solution {

  public int largestRectangleArea(int[] heights) {

​    Stack<Integer> stack = new Stack<>();

​    // 数组扩容

​    int[] newHeights = new int[heights.length + 2];

​    newHeights[0] = 0;

​    newHeights[newHeights.length - 1] = 0;

​    for (int i = 0; i < heights.length; i++) {

​      newHeights[i + 1] = heights[i];

​    }

​    heights = newHeights; // 改变数组引用

​    stack.add(0);

​    int result = 0;

​    for (int i = 1; i < heights.length; i++) {

​      if (heights[i] > heights[stack.peek()]) { // 入栈

​        stack.add(i);

​      } else if (heights[i] == heights[stack.peek()]) { 

​        stack.pop(); // 弹出

​        stack.add(i); // 入栈

​      } else {

​        while (heights[i] < heights[stack.peek()]) {

​          int mid = stack.peek(); // 当前数值柱子

​          stack.pop();

​          int left = stack.peek();

​          int right = i;

​          int w = right - left - 1;

​          int h = heights[mid];

​          result = Math.max(result, w * h);

​        }

​        stack.add(i);

​      }

​    }

​    return result;

  }

}
3.复杂度分析:

时间复杂度:O(n).

空间复杂度:O(n).符合单调递减的情况时,全部入栈。

相关推荐
眼镜哥(with glasses)27 分钟前
蓝桥杯 国赛2024python(b组)题目(1-3)
数据结构·算法·蓝桥杯
int型码农5 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
UFIT5 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面5 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked935 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
怀旧,5 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法
积极向上的向日葵6 小时前
有效的括号题解
数据结构·算法·
GIS小天6 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票
_Itachi__6 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
不忘不弃6 小时前
计算矩阵A和B的乘积
线性代数·算法·矩阵