LeetCode Largest Rectangle in Histogram

来源:互联网 发布:淘宝有卖纯种圣伯纳犬 编辑:程序博客网 时间:2024/05/29 14:09

题目

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.

 

求数值表达的区域中的最大矩形面积。

n^2的方法不难想到,会超时。

可以注意到:

如果某个序列是递增的,那么这部分中最大的矩形的右边必然是序列的右侧;

因为向左改变右侧的边界只会使长度变短,而高度不会变高。

 

O(n)的方法:

从左向右扫描,通过堆栈保存递增序列的各个元素的位置。

1、如果当前位置大于堆栈尾,压入。

2、否则,从堆栈尾弹出。计算面积,高为弹出位置元素的值,而长度为当前位置到堆栈尾(弹出后)的位置。刷新。

 

注意堆栈为空时的处理,此时长度是到头(0位置)的。

可在原序列后增加一个高度为0的元素,使得最后尾部的递增序列可以被计算面积。

 

代码:

class Solution {public:    int largestRectangleArea(vector<int> &height) {        int len=height.size();height.push_back(0);//尾部添加标记0vector<int> stack;//保存递增序列的堆栈int pos=0,h;//处理到的位置,堆栈弹出用int area,max_area=0;//临时面积,最大面积while(pos<=len){if(stack.empty()||height[pos]>=height[stack.back()])//堆栈空或者是递增序列,压入stack.push_back(pos++);else//否则{h=stack.back();//出栈stack.pop_back();if(!stack.empty())//栈非空,宽度到弹出的位置area=height[h]*(pos-stack.back()-1);else//堆栈空,宽度到头(0)area=height[h]*pos;if(area>max_area)//刷新max_area=area;}}height.pop_back();//去除添加的标记0return max_area;    }};


 

 

 

0 0