LeetCode84——Largest Rectangle in Histogram
2016-01-27 22:34
344 查看
LeetCode84——Largest Rectangle in Histogram
在柱状图中找到面积最大的矩形。原题
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 heights = [2,1,5,6,2,3],
return 10.
分析1
考虑回文串的一种从中间往两头找的算法,首先遍历,对于每一个柱状图来说,向左右搜索,直到找到比他小的柱状图(假设为l和r),这样算出该柱状图的对应的矩形的面积为(r-l+1)*heights[cur]。这是我自己想出来的,很遗憾,它的复杂度为O(n2),提交之后对于大规模的数据来说超时。
代码
class Solution { public: int largestRectangleArea(vector<int>& heights) { int nSize = heights.size(); int i = 0; int maxSize = 0; while (i < nSize) { int j = i+1; int k = i-1; int sum = heights[i]; while (k > 0&&heights[k]>heights[i]) { k--; sum += heights[i]; } while (j<nSize&&heights[j]>heights[i]) { j++; sum += heights[i]; } maxSize = max(maxSize, sum); i++; } return maxSize; } };
分析2
参考codeganker的解法,首先,我们知道,在计算矩形时,对于索引i所对应的的柱状图,它一定是由它“生成的”矩形中最小的柱状图。那么我们在计算时,假设现在从i出发往左右搜索,找到左边第一个比heights[i]小的索引l,和右边第一个比heights[i]小的索引r,那么r和l之间就是我们要找的由索引i对应的柱状图生成的矩形区域。
现在对heights进行遍历,将柱状图的大小从小到大的顺序,将索引压栈,那么对于栈顶元素来说(假设其索引为cur),他对应的r即为当前遍历的位置,他对应的l则时他的上一个进栈的索引(有可能栈为空,则这个索引为-1),这样,计算过的索引弹栈,最终得到结果,最后为了计算最后一个元素的生成矩阵,我们在heights的末尾插入0,方便计算。
代码
class Solution { public : int largestRectangleArea(vector<int>& heights){ heights.push_back(0); int nSize = heights.size(); stack<int> index; int maxSize = 0; int i=0; while(i<nSize) { if (index.empty()||heights[i]>heights[index.top()]) { index.push(i); i++; } else { int j = index.top(); index.pop(); maxSize = max(maxSize, heights[j]*(index.empty() ? i : (i - index.top() - 1) )); } } return maxSize; } };
参考
https://siddontang.gitbooks.io/leetcode-solution/content/array/largest_rectangle_in_histogram.htmlhttp://blog.csdn.net/linhuanmars/article/details/20524507
相关文章推荐
- 学习C#2
- OCiOS开发:多线程与消息通知
- 解决Eclipse建立Maven项目后无法建立src/main/java资源文件夹的办法
- js 完全分离 window.onload=
- 我的github
- LeetCode题解--1. Two Sum(和为S的两个数字)
- UIScrollViewAndUIPageController结合使用
- 如何开始使用OpenStack命令行和API
- asm基础——使用nasm和bochs学习汇编
- 文件输入输出
- linux - 创建用户
- Java中的Date Time 与SQL Server 2005里的Datetime 之间的交互
- 为何有大量show slave status产生
- 修改Oracle字符集
- 谷歌和ESRI眼中的Web Mercator
- 解决“重新安装vmware-tools”灰色而无法安装的问题
- WM_PAINT详解和WM_ERASEBKGND
- 课程学生列表
- 关于js中两种定时器的设置及清除
- 函数的参数