码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode刷题笔记】Largest Rectangle in Histogram

时间:2014-07-24 22:39:53      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   width   2014   for   

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.

bubuko.com,布布扣

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

bubuko.com,布布扣

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.


 

题解:在网上研究了好久才弄懂。

首先,需要一个栈,栈里面存放每个条的索引,当当前的元素大于栈顶的元素或者栈为空时,将当前元素入栈;

当当前元素小于栈顶元素的时候,将栈顶元素弹出来,索引记录在top变量上,那么还有两种可能:

  • 栈不为空,如下图所示,从栈顶的条到top所指的条(当前出栈的条)的高度一定大于等于top的高度(否则它们应该还在栈里面),一共有(top-栈顶索引-1)个条,而top~i这一段的高度也一定大于等于top的高度(否则指针不会有top刚出栈而指针已经移动到i),一共有(i-top)个条(包括top自己),所以top所能向左和向右到达的最大延伸长度为(top-栈顶索引-1)+(i-top)=(i-栈顶索引-1),产生的最大面积为height[top] * (i-栈顶索引-1) 。

bubuko.com,布布扣

  • 栈为空,如下图所示,说明top所指的条(当前出栈的条)向左延伸可以到达最左边,向右延伸可以到达i,一共有 i 个条,产生的最大面积为height[top] * i

bubuko.com,布布扣

所以当元素top出栈的时候,它所能产生的最大面积为 height[top] * (stack.isEmpty()?i:i-stack.top()-1) 。 

总结一下栈的意义,对于为位置 i 处的条来说,栈中存放的元素是可以一路“延展”至 i 的条,所以它们都比 i 小,都可以利用 i 来增加自己产生的矩形的最大面积,而那些比 i 高的条已经不能通过 i 继续往右延展了,即它们往右能够延展到的部分已经被 i 阻拦了,我们就可以计算它们此时已经左右延展的距离来计算它们所能产生的矩形的最大面积了。比如下图中i = 4的时候,红色的条已经不能通过4继续往右扩展,它往右扩展被4给挡住了,所以它要出栈,而绿色的条比4矮,它仍然可以利用4增大它产生的矩形的面积,所以它不需要出栈,因为我们还没确定它的右边界。

bubuko.com,布布扣

最后,有两点trick:

  • 一是比如上图的情况,遍历完成后,绿色的条还在栈里面,所以我们要在所有的条最后增加一个长度为0的条,它可以把栈中所有的条都弹出来,我们就得到了所有的条能够产生的最大矩形的面积了。
  • 二是在有元素弹出栈后,i 指针要保持不动,因为有可能它前面的元素也比 i 指向的条矮,需要出栈。

代码如下:

 1 public class Solution {
 2     public int largestRectangleArea(int[] height) {
 3         if(height == null || height.length == 0)
 4             return 0;
 5         Stack<Integer> index = new Stack<Integer>();
 6         int totalMax = 0;
 7         ArrayList<Integer> newHeight = new ArrayList<Integer>();
 8         for(int i:height) newHeight.add(i);
 9         newHeight.add(0);
10         
11         
12         for(int i = 0;i < newHeight.size();i++){
13             if(index.isEmpty() || newHeight.get(i) >= newHeight.get(index.peek()))
14                 index.push(i);
15             else{
16                 int top = index.pop();
17                 totalMax = Math.max(totalMax,newHeight.get(top) * (index.isEmpty()?i:i-top));
18                 i--;
19             }
20         }
21         
22         return totalMax;
23     }
24 }

【leetcode刷题笔记】Largest Rectangle in Histogram,布布扣,bubuko.com

【leetcode刷题笔记】Largest Rectangle in Histogram

标签:style   blog   http   color   io   width   2014   for   

原文地址:http://www.cnblogs.com/sunshineatnoon/p/3866385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!