您的位置:首页 > 其它

lintcode: Largest Rectangle in Histogram

2016-04-18 22:14 369 查看
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.

方法一

O(n^2)

对于每个bar,找出bar是最矮的范围,求出一个面积;遍历所有bar,得到max面积。

超时

class Solution {
public:
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &height) {
// write your code here

int maxArea=0;

for(int i=0;i<height.size();i++){

int left;
if(i==0){
left=i;
}else{
left=i-1;
while(left>=0 && height[left]>=height[i]) left--;
left++;
}

int right;
if(i==height.size()-1){
right=i;
}else{
right=i+1;
while(right<=height.size()-1 && height[right]>=height[i]) right++;
right--;
}

int area=(right-left+1)*height[i];

if(area>maxArea){
maxArea=area;
}

}

return maxArea;
}
};


方法2

用递增栈

/article/5789867.html

class Solution {
public:
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &height) {
// write your code here

stack<int> stk;

int maxArea=0;

int i=0;

vector<int> h(height);
//后面加个0
h.push_back(0);

while(i<h.size()){
if(stk.empty() || h[i]>=h[stk.top()]){
stk.push(i);
i++;
}else{
int t=stk.top();
stk.pop();

int area=h[t]*(stk.empty()?i:(i-stk.top()-1));
if(area>maxArea){
maxArea=area;
}
}
}

return maxArea;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: