Largest_Rectangle_in_Histogram
来源:互联网 发布:易语言网页填表源码 编辑:程序博客网 时间:2024/06/09 16:53
题目描述:
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.
(给定n个非负整数表示柱状图的条高如果每个条的宽度为1,则在柱状图中找到最大矩形的面积。以上是一个柱状图,每个栏的宽度为1,高度= [ 2,1,5,6,2,3 ]。最大矩形显示在阴影区域,面积为10单位。)
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
.
public class Largest_Rectangle_in_Histogram {public static int largestRectangleArea(int[] heights) {if(heights.length==0)return 0;int result = 0;//存放的是序列的下标Stack<Integer> stack = new Stack<Integer>();for(int i=0;i<heights.length;i++){while(!stack.isEmpty()&&heights[i]<heights[stack.peek()]){int index = stack.pop();int height = heights[index];//这句话说白了就是如果你是最后一个出栈的,那说明你就是之前最小的数,那么你的宽就是i.int width = stack.isEmpty()?i:i-stack.peek()-1;result = Math.max(result,width*height);}stack.push(i);}while(!stack.isEmpty()){int index = stack.pop();int height = heights[index];int width = stack.isEmpty()?heights.length:heights.length-stack.peek()-1;result = Math.max(result,width*height);} return result; }public static void main(String[] args) {int heights[] = {2,1,2};System.out.println(largestRectangleArea(heights));}}
阅读全文
0 0
- Largest_Rectangle_in_Histogram
- Qt 之 解析wav文件的头信息(详细分析、对比不同wav文件的数据)
- LibreOJ 6178「美团 CodeM 初赛 Round B」景区路线规划
- Tablayout与XListView
- 树莓派GPIO入门05-驱动数码管显示数字(嵌入式很好的链接平台,见解深刻)
- ImageLoader的使用
- Largest_Rectangle_in_Histogram
- webpack配置
- 常用的依赖和权限
- 学习验证
- canvas scale()画布缩放的使用
- 博客迁移到简书
- json解析数据流代码
- Qt之实现录音播放及raw(pcm)转wav格式
- 内存池的实现