lintcode(122)直方图最大矩形覆盖
来源:互联网 发布:淘宝固本安宫止血汤 编辑:程序博客网 时间:2024/05/16 16:00
Description:
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.
Explanation:
给出 height = [2,1,5,6,2,3],返回 10
Solution:
计算以当前值为高的矩形面积,所以要找到它的左右边界。建立栈,存储当前元素在数组中的位置。将数组元素一次推入栈中,如果它比栈顶元素小,则栈顶元素的右边界出现了,现在确定他的左边界。此时将栈顶元素出栈。栈中都是比当前元素小的值,因为比当前值大的都因当前值而出栈,所以,可以借此确定当前矩形的左边界,如果栈为空,说明当前元素是栈中最小值,左边界就是0。知道左右边界之后就可以计算面积了,高度是当前值,宽度是 i 或者 i-stack.peek()-1,为什么再-1?因为是左边界,已经不在矩形范围内了,当前值已经出栈了。
public class Solution { /** * @param height: A list of integer * @return: The area of largest rectangle in the histogram */ public int largestRectangleArea(int[] height) { // write your code here if(height.length == 0) return 0; int[] high = Arrays.copyOf(height , height.length + 1); int result = 0; Stack<Integer> rank = new Stack<Integer>(); for(int i = 0;i<high.length;i++){ while(!rank.isEmpty() && high[i] < high[rank.peek()] ){ int area = high[rank.pop()]*(rank.isEmpty()?i:i-rank.peek() - 1); result = Math.max(result , area); } rank.push(i); } return result; }}
阅读全文
0 0
- lintcode(122)直方图最大矩形覆盖
- LintCode 直方图最大矩形覆盖
- lintcode:直方图最大矩形覆盖
- LintCode-直方图最大矩形覆盖
- 直方图最大矩形覆盖-LintCode
- lintcode 直方图最大矩形覆盖与最大子矩阵
- 直方图最大矩形覆盖
- lintcode[122]:直方图内最大矩形面积
- 【LeetCode】直方图最大矩形覆盖(栈)
- 直方图最大面积矩形
- 直方图内最大矩形
- 直方图内最大矩形
- 直方图内最大矩形
- 直方图最大矩形
- 直方图最大矩形面积
- 直方图内最大矩形
- 直方图包含最大矩形
- 直方图内最大矩形
- jQuery系列之获得元素值(五)
- 刷清橙OJ--A1068.回形取数
- Log4j 配置使用
- Linux 2.6内核Makefile浅析
- 如何在命名空间中用use引入类、方法,并创建别名
- lintcode(122)直方图最大矩形覆盖
- Android Application启动流程分析
- android有了eventbus,一切与关界面通信问题迎刃而解。
- 如何封装一个通用的PopupWindow
- uva10305- Ordering Tasks(拓扑排序)
- 从高考到程序员
- 字/字节/字长
- C#——面向对象——泛型——泛型类
- Android中DatePicker的使用