[leetcode]84. Largest Rectangle in Histogram直方图中的最大矩形
2024-10-13 08:44:48
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
Example:
Input: [2,1,5,6,2,3]
Output: 10
题意:
给定一个直方图,求其能覆盖的最大矩形。
思路:
以下是O(n2) 的时间复杂度解法
当 i= 0 1 2 3 4
area= 2*1 4*1 6*1 5*1 3*1
2*2 4*2 5*2 3*2
2*3 4*3 3*3
2*4 3*4
2*5
以height[i]为临界,每次比较其左侧的所有height谁更小,更新minHeight, 更新当前maxArea
class Solution {
public int largestRectangleArea(int[] heights) {
int maxArea = 0;
for(int i = 0; i < heights.length; i++){
int minHeight = heights[i]; //以height[i]为临界
for(int j = i; j >= 0; j--){ // 每次比较其左侧的所有height谁更小
minHeight = Math.min(minHeight, heights[j]);
maxArea = Math.max(maxArea, minHeight * (i - j + 1));
}
}
return maxArea;
}
}
以下是O(n) 的时间复杂度解法
维护一个单调栈monoStack,数组中每个元素的index都入栈、出栈
代码:
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> s = new Stack<>();
int area = 0;
for(int i=0; i<= heights.length;){
int value = i< heights.length ? heights[i]: 0;
if(s.isEmpty() || value> heights[s.peek()]){
s.push(i);
i++;
}else{
int temp = s.pop();
area = Math.max(area, heights[temp] * (s.isEmpty() ? i: (i-s.peek()-1)));
} }
return area;
}
}
最新文章
- 在ASP.NET MVC项目中使用React
- property内存管理策略
- HashSet与HashMap的区别
- java 15 -7 ListIterator 的特有方法
- 在后台CS文件里面,隐藏和显示Repeater里面控件
- FloatingActionButton 完全解析[Design Support Library(2)]
- ajax 简单操作
- android进度条
- stata
- 学习笔记——门面模式Facade
- 房上的猫:经典排序算法 - 冒泡排序Bubble sort
- 项目实战10.1—企业级自动化运维工具应用实战-ansible
- February 26th, 2018 Week 9th Monday
- Google Maps V3 之 路线服务
- vue-cli关闭eslint及配置eslint
- Mac下的安装 mongodb
- redis如何后台启动
- bzoj 2739 最远点——分治处理决策单调性
- JAVA-SpringMVC开发第一个应用
- codeforces水题100道 第十二题 Codeforces Beta Round #91 (Div. 2 Only) A. Lucky Division (brute force)