leetcode——Largest Rectangle in Histogram
2015-06-14 16:49
429 查看
原题
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 =
The largest rectangle is shown in the shaded area, which has area =
For example,
Given height =
return
解:
int largestArea(vector<int> &height)
{
stack<int> s;
int res=0;
int max=0;
int topData;
int i;
for(i=0; i<height.size(); )
{
if(s.empty() || height[i]>=height[s.top()])//使用保持栈中的数据递增,否则计算出矩阵的大小
{
s.push(i++);
}
else
{
topData=s.top();
s.pop();
max=height[topData]*(s.empty()?i:i-s.top()-1);//只要s不为空,那么一定满足在(s.top,i)之间的数据都大于等于height[topData]
if(max>res)
res=max;
}
}
while(!s.empty())//别忘了考虑最后i到头的情况
{
topData=s.top();
s.pop();
max=height[topData]*(s.empty()? i : i-s.top()-1);
if(max>res)
res=max;
}
return res;
}
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 =
10unit.
For example,
Given height =
[2,1,5,6,2,3],
return
10.
解:
int largestArea(vector<int> &height)
{
stack<int> s;
int res=0;
int max=0;
int topData;
int i;
for(i=0; i<height.size(); )
{
if(s.empty() || height[i]>=height[s.top()])//使用保持栈中的数据递增,否则计算出矩阵的大小
{
s.push(i++);
}
else
{
topData=s.top();
s.pop();
max=height[topData]*(s.empty()?i:i-s.top()-1);//只要s不为空,那么一定满足在(s.top,i)之间的数据都大于等于height[topData]
if(max>res)
res=max;
}
}
while(!s.empty())//别忘了考虑最后i到头的情况
{
topData=s.top();
s.pop();
max=height[topData]*(s.empty()? i : i-s.top()-1);
if(max>res)
res=max;
}
return res;
}
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#数据结构与算法揭秘二
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#常见算法面试题小结
- JavaScript 组件之旅(二)编码实现和算法
- JavaScript数据结构和算法之图和图算法