题目:
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.
Example:
Input: [2,1,5,6,2,3] Output: 10
采用从中间向两边,寻找最大面积。不低于当前元素的连续的元素可以组成正方形 (TLE)
代码如下:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int MaxRecArea = 0;
int left,right;
for(int i = 0; i < heights.size();i++)
{
if(i > 0 && heights[i] == heights[i-1])
continue;
left = i - 1;
right = i + 1;
while(left >= 0)
{
if(heights[left] >= heights[i])
left--;
else
break;
}
while(right < heights.size())
{
if(heights[right] >= heights[i])
right++;
else
break;
}
int curArea = (right - left - 1) * heights[i];
MaxRecArea = max(MaxRecArea,curArea);
}
return MaxRecArea;
}
};
将上面的代码复杂度O(n^2)将至 O(n),使用两个长度为m的数组分别记录每个位置的左边界,右边界。
初始化0位置左边界-1,m-1位置的右边界m
如果 heights[ i - 1] >= heights[ i ] , 则 p = htleft[i - 1] , 如果 heights[p] > = heights[i], 则 p = htleft[p] 如此循环,直到,heights[p] < heights[i], 则 htleft[i] = p, htright的求法类似. 注意边界 ,p 不能越界,而且不能忽略边界值 p >= 0
代码如下:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int m = heights.size();
if(m == 0)
return 0;
int MaxArea = 0;
vector<int> htleft(m,-1);
vector<int> htright(m,m);
for(int i = 1; i < m; i++)
{
int p = i - 1;
while(p >= 0 && heights[p] >= heights[i])
p = htleft[p];
htleft[i] = p;
}
for(int i = m - 2; i >= 0; i--)
{
int p = i + 1;
while(p < m && heights[p] >= heights[i])
p = htright[p];
htright[i] = p;
}
for(int i = 0; i < m; i++)
{
int area = heights[i] * (htright[i] - htleft[i] - 1);
MaxArea = max(MaxArea,area);
}
return MaxArea;
}
};