Largest Rectangle in Histogram leetcode java
2024-10-19 11:51:32
题目:
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.
For example,
Given height = [2,1,5,6,2,3]
,
return 10
.
题解:
这道题自己是完全没想到用栈了。。
有个很完整很详细很好的讲解在这里: http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
我就不写了。贴一下上面提到的代码吧。
O(n^2)的:
1 public int largestRectangleArea(int[] height) {
2 // Start typing your Java solution below
3 // DO NOT write main() function
4 int[] min = new int[height.length];
5 int maxArea = 0;
6 for(int i = 0; i < height.length; i++){
7 if(height[i] != 0 && maxArea/height[i] >= (height.length - i)) {
8 continue;
9 }
for(int j = i; j < height.length; j++){
if(i == j) min[j] = height[j];
else {
if(height[j] < min[j - 1]) {
min[j] = height[j];
}else min[j] = min[j-1];
}
int tentativeArea = min[j] * (j - i + 1);
if(tentativeArea > maxArea) {
maxArea = tentativeArea;
}
}
}
return maxArea;
}
O(n)的:
1 public int largestRectangleArea2(int[] height) {
2 Stack<Integer> stack = new Stack<Integer>();
3 int i = 0;
4 int maxArea = 0;
5 int[] h = new int[height.length + 1];
6 h = Arrays.copyOf(height, height.length + 1);
7 while(i < h.length){
8 if(stack.isEmpty() || h[stack.peek()] <= h[i]){
9 stack.push(i++);
}else {
int t = stack.pop();
maxArea = Math.max(maxArea, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return maxArea;
}
最新文章
- github如何删除一个(repository)仓库
- 对于似1/(1+x^4)型的不定积分的总结
- 12月07日《奥威Power-BI智能分析报告制作方法 》腾讯课堂开课啦
- [转]mongodb与mysql相比的优缺点
- Cordova4.0 系列 -- 基本环境搭建(1)
- C语言每日一题之No.3
- VS中制作安装文件
- 限额类费用报销单N+1原则
- 【Linux学习】 写一个简单的Makefile编译源码获取当前系统时间
- PowerShell中的输出
- Linux下查看Web服务器当前的并发连接数和TCP连接状态
- MongoDB学习笔记-认识MongoDB
- WPF 多语言解决方案 - Multilingual App Toolkit
- 【3】测试搭建成功的单机hadoop环境
- React 组件间通讯
- java.io包下适配和装饰模式的使用
- [记录]MySQL 查询无法导出到文件
- update-alternatives关键解疑
- CrazySNS has on line - And you&#39;ll see why 1984 won&#39;t be like ";1984.";
- openvpn push ";route
热门文章
- Android 使用ViewPager 做的半吊子的图片轮播
- python pip 不能用报错: ImportError: No module named _internal
- 20162307 课堂测试 hash
- Linux免密登录
- MAC下安装多版本JDK和切换几种方式
- 监听当点击微信等app的返回按钮或者浏览器的上一页或后退按钮的事件
- spring @Transactional注解无效
- KVM资源划分分配技巧
- Java学习笔记_22_Set接口的实现类
- Digital Adjustment of DC-DC Converter Output Voltage in Portable Applications