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;
}
}

最新文章

  1. 在ASP.NET MVC项目中使用React
  2. property内存管理策略
  3. HashSet与HashMap的区别
  4. java 15 -7 ListIterator 的特有方法
  5. 在后台CS文件里面,隐藏和显示Repeater里面控件
  6. FloatingActionButton 完全解析[Design Support Library(2)]
  7. ajax 简单操作
  8. android进度条
  9. stata
  10. 学习笔记——门面模式Facade
  11. 房上的猫:经典排序算法 - 冒泡排序Bubble sort
  12. 项目实战10.1—企业级自动化运维工具应用实战-ansible
  13. February 26th, 2018 Week 9th Monday
  14. Google Maps V3 之 路线服务
  15. vue-cli关闭eslint及配置eslint
  16. Mac下的安装 mongodb
  17. redis如何后台启动
  18. bzoj 2739 最远点——分治处理决策单调性
  19. JAVA-SpringMVC开发第一个应用
  20. codeforces水题100道 第十二题 Codeforces Beta Round #91 (Div. 2 Only) A. Lucky Division (brute force)

热门文章

  1. &lt;ROS&gt; 通讯方式之 Action
  2. git 更新远程分支列表
  3. 铁板纹理 Base Shape
  4. 配置iis支持json解析,配置ssi
  5. Reachability实时监控网络变化
  6. Kafka介绍与消息队列
  7. 使用css实现时间轴
  8. eclipse常用快捷键整理
  9. 如何让大小一定的span能够包含“容不下”的内容
  10. xlrd 和xlwt 对Excel的操作