您的位置:首页 > 其它

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.html

http://blog.csdn.net/linhuanmars/article/details/20524507
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: