http://blog.csdn.net/abcbc/article/details/8943485

具体的题目描述为:

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.

这道题可以有两个解法。

解法一是穷举法,对于直方图的每一个右边界,穷举所有的左边界。将面积最大的那个值记录下来。时间复杂度为O(n^2). 单纯的穷举在LeetCode上面过大集合时会超时。可以通过选择合适的右边界,做一个剪枝(Pruning)。观察发现当height[k] >= height[k - 1]时,无论左边界是什么值,选择height[k]总会比选择height[k - 1]所形成的面积大。因此,在选择右边界的时候,首先找到一个height[k] < height[k - 1]的k,然后取k - 1作为右边界,穷举所有左边界,找最大面积。

Java代码:

 // O(n^2) with pruning
public int largestRectangleArea1(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
int area = 0;
for (int i = 0; i < height.length; i++) {
for (int k = i + 1; k < height.length; k++) {
if (height[k] < height[k - 1]) {
i = k - 1;
break;
} else {
i = k;
}
}
int lowest = height[i];
for (int j = i; j >= 0; j--) {
if (height[j] < lowest) {
lowest = height[j];
}
int currArea = (i - j + 1) * lowest;
if (currArea > area) {
area = currArea;
}
}
}
return area;
}

虽然上面的解法可以过大集合,但是不是最优的方法,下面介绍使用栈的优化解法。时间复杂度为O(n).

此解法的核心思想为:一次性计算连续递增的区间的最大面积,并且考虑完成这个区间之后,考虑其前、后区间的时候,不会受到任何影响。也就是这个连续递增区间的最小高度大于等于其前、后区间。

这个方法非常巧妙,最好通过一个图来理解:

假设输入直方图为:int[] height = {2,7,5,6,4}.

这个方法运行的时候,当遇到height[2] == 5的时候,发现其比之前一个高度小,则从当前值(5)开始,向左搜索比当前值小的值。当搜索到最左边(2)时,比5小,此时计算在height[0]和height[2]之间的最大面积,注意不包括height[0]和和height[2]。height[1]以红色标出的这个区域就被计算完成。同样的方法,计算出绿色和粉色的面积。

因此这个方法需要使用两个栈。第一个栈为高度栈heightStack,用于记录还没有被计算过的连续递增的序列的值。第二个栈为下标栈indexStack,用于记录高度栈中对应的每一个高度的下标,以计算宽度。

算法具体执行的步骤为:

若heightStack为空或者当前高度大于heightStack栈顶,则当前高度和当前下标分别入站(下面有一个解法可以只用一个栈即可,用栈来保存下标,而高度由下标很容易得到)。所以heightStack记录了一个连续递增的序列。

若当前高度小于heightStack栈顶,heightStack和indexStack出栈,直到当前高度大于等于heightStack栈顶。出栈时,同时计算区间所形成的最大面积。注意计算完之后,当前值入栈的时候,其对应的下标应该为最后一个从indexStack出栈的下标。比如height[2]入栈时,其对应下标入栈应该为1,而不是其本身的下标2。如果将其本身下标2入栈,则计算绿色区域的最大面积时,会忽略掉红色区域。

C++代码:

class Solution {
public:
int largestRectangleArea(vector<int> &height) {
if(height.size() == 0) return 0; int res = 0;
vector<int> tmp = height;
tmp.push_back(0); // Important stack<int> s;
for(int i = 0; i < tmp.size(); i++)
{
if(s.empty() || (!s.empty() && tmp[i] >= tmp[s.top()])) s.push(i);
else{
while(!s.empty() && tmp[s.top()] > tmp[i])
{
int idx = s.top(); s.pop();
int width = s.empty() ? i : (i-s.top()-1);
res = max(res, tmp[idx] * width);
}
s.push(i); // Important
}
}
return res;
}
};

  

Java代码:

// O(n) using two stacks
public int largestRectangleArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
int area = 0;
java.util.Stack<Integer> heightStack = new java.util.Stack<Integer>();
java.util.Stack<Integer> indexStack = new java.util.Stack<Integer>();
for (int i = 0; i < height.length; i++) {
if (heightStack.empty() || heightStack.peek() <= height[i]) {
heightStack.push(height[i]);
indexStack.push(i);
} else if (heightStack.peek() > height[i]) {
int j = 0;
while (!heightStack.empty() && heightStack.peek() > height[i]) {
j = indexStack.pop();
int currArea = (i - j) * heightStack.pop();
if (currArea > area) {
area = currArea;
}
}
heightStack.push(height[i]);
indexStack.push(j);
}
}
while (!heightStack.empty()) {
int currArea = (height.length - indexStack.pop()) * heightStack.pop();
if (currArea > area) {
area = currArea;
}
}
return area;
}

  

更新:

在网上发现另外一个使用一个栈的O(n)解法,代码非常简洁,栈内存储的是高度递增的下标。对于每一个直方图高度,分两种情况。1:当栈空或者当前高度大于栈顶下标所指示的高度时,当前下标入栈。否则,2:当前栈顶出栈,并且用这个下标所指示的高度计算面积。而这个方法为什么只需要一个栈呢?因为当第二种情况时,for循环的循环下标回退,也就让下一次for循环比较当前高度与新的栈顶下标所指示的高度,注意此时的栈顶已经改变由于之前的出栈。

Java代码:

// O(n) using one stack
public int largestRectangleArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
int area = 0;
java.util.Stack<Integer> stack = new java.util.Stack<Integer>();
for (int i = 0; i < height.length; i++) {
if (stack.empty() || height[stack.peek()] < height[i]) {
stack.push(i);
} else {
int start = stack.pop();
int width = stack.empty() ? i : i - stack.peek() - 1;
area = Math.max(area, height[start] * width);
i--;
}
}
while (!stack.empty()) {
int start = stack.pop();
int width = stack.empty() ? height.length : height.length - stack.peek() - 1;
area = Math.max(area, height[start] * width);
}
return area;
}

  

LeetCode: Largest Rectangle in Histogram(直方图最大面积)的更多相关文章

  1. 【LeetCode】84. Largest Rectangle in Histogram——直方图最大面积

    Given n non-negative integers representing the histogram's bar height where the width of each bar is ...

  2. [LeetCode] Largest Rectangle in Histogram 直方图中最大的矩形

    Given n non-negative integers representing the histogram's bar height where the width of each bar is ...

  3. [LeetCode] Largest Rectangle in Histogram O(n) 解法详析, Maximal Rectangle

    Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar height ...

  4. leetcode Largest Rectangle in Histogram 单调栈

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052343.html 题目链接 leetcode Largest Rectangle in ...

  5. LeetCode: Largest Rectangle in Histogram 解题报告

    Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar height ...

  6. [LeetCode] 84. Largest Rectangle in Histogram 直方图中最大的矩形

    Given n non-negative integers representing the histogram's bar height where the width of each bar is ...

  7. LeetCode 84. Largest Rectangle in Histogram 直方图里的最大长方形

    原题 Given n non-negative integers representing the histogram's bar height where the width of each bar ...

  8. [leetcode]84. Largest Rectangle in Histogram直方图中的最大矩形

    Given n non-negative integers representing the histogram's bar height where the width of each bar is ...

  9. [LeetCode] Largest Rectangle in Histogram 解题思路

    Given n non-negative integers representing the histogram's bar height where the width of each bar is ...

随机推荐

  1. Ruby升级的最新方法

    今天安装cocoapods时候出现了下面的提示Error installing pods:active support requires Ruby version >= 2.2.0这个需求的意思 ...

  2. python作用域和多继承

    python作用域 python无块级作用域 看c语言代码: #include<stdio.h> int main() { > ) { ; } printf("i = %d ...

  3. 面试题目——《CC150》数学与概率

    面试题7.2:三角形的三个顶点上各有一只蚂蚁.如果蚂蚁开始沿着三角形的边爬行,两只或三只蚂蚁撞到一起的概率有多大?假定每只蚂蚁会随机选一个方向,每个方向被选到的几率相等,而且三只蚂蚁的爬行速度相同. ...

  4. Trie tree实践

    1.Trie树 Trie树即字典树或前缀树, 2.实践 代码实践如下: package cn.edu.buaa.trie; import java.util.HashSet; /** * @autho ...

  5. Node.js入门笔记(4):文件系统(fs)

    文件系统(FileSystem) 文件系统模块 对于文件无外乎创建修改添加. File System - 文件系统模块 - require('fs') fs模块是核心模块,需要使用require导入后 ...

  6. c语言求数组长度

    在定义数组的函数内 int arr[] = {12.12}; int length; length = ]; 在别的函数中作为引用数据类型引入时,以上方法失效: 解决方法1:再传一个int 类型的长度 ...

  7. 今天又学了一招,牛逼!!!解决"-bash:No such file or directory"问题

    今天在64服务器上:发现好像bash 坏了,用户名前边   用-bash 显示,,前几天就发现这个问题,,,但是当时忙没有解决,,,,,今天来看看到底是怎么回事! File Exists but... ...

  8. Spring实现初始化和销毁bean之前进行的操作,三种方式

    关于在spring  容器初始化 bean 和销毁前所做的操作定义方式有三种: 第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作 第二 ...

  9. PHP打印测试,PHP调试技巧

    第一步: 在 php.ini 中,将 display_errors 设置为 On: 第二步: 在 框架的 开始处,添加如下代码: <?php if (isset($_GET['debug'])) ...

  10. 限制帐号同时两处以上登录-ASP.NET

    ///登录页面 Hashtable haol = (Hashtable)Application["olTable"]; if (haol == null) { haol = new ...