084 Largest Rectangle in Histogram 柱状图中最大的矩形
2024-09-04 19:34:29
给出 n 个非负整数来表示柱状图的各个柱子的高度,每个柱子紧挨彼此,且宽度为 1 。
您的函数要能够求出该柱状图中,能勾勒出来的最大矩形的面积。
详见:https://leetcode.com/problems/largest-rectangle-in-histogram/description/
Java实现:
方法一:遍历数组,每找到一个局部峰值,就向前遍历所有的值,算出共同的矩形面积,每次对比保留最大值。
class Solution {
public int largestRectangleArea(int[] heights) {
int res=0;
int n=heights.length;
for(int i=0;i<n;++i){
if(i+1<n&&heights[i]<=heights[i+1]){
continue;
}
int minH=heights[i];
for(int j=i;j>=0;--j){
minH=Math.min(minH,heights[j]);
int area=minH*(i-j+1);
res=Math.max(res,area);
}
}
return res;
}
}
方法二:
class Solution {
public int largestRectangleArea(int[] heights) {
int n=heights.length;
if (heights == null || n == 0){
return 0;
}
int res=0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < n; ++i) {
//如果高度递增,那么一次入栈。
if (stack.isEmpty() || heights[stack.peek()] <= heights[i]) {
stack.push(i);
}
//如果当前柱比栈顶的低,那么把栈顶的拿出来,计算所有已经出栈的最大面积。
else {
int start = stack.pop();
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
res = Math.max(res, heights[start] * width);
--i;
}
} //循环过后栈中是递增的条目,计算在栈中递增条目的最大面积。
while (!stack.isEmpty()) {
int start = stack.pop();
int width = stack.isEmpty() ? n : n - stack.peek() - 1;
res = Math.max(res, heights[start] * width);
}
return res;
}
}
参考:https://www.cnblogs.com/grandyang/p/4322653.html
最新文章
- linux bash 笔记
- iOS 常见 Crash 及解决方案
- [转载] C++位运算:将一个4字节整数的二进制表示中的001替换为011
- 高版本myeclipse破解以及优化
- .Net 代码安全保护产品DNGuard HVM使用
- Map集合中value()方法与keySet()、entrySet()区别
- Eclipse vim插件安装使用
- python作业day4计算器
- 教你在mac上配置adb环境变量
- webBrowser中操作网页元素全攻略
- iOS多线程与网络开发之发送接收server信息
- bat给文件追加换行内容
- python subprocess.Popen 控制台输出 实时监控百度网ping值
- 各种MM(存储器)含义
- Tensorflow 中的优化器解析
- 点击DIV随机换颜色
- crontab详细用法
- intellij 快捷键整理
- nuclio dokcer 运行测试
- [SCOI2007]修车(建图好题)