0
点赞
收藏
分享

微信扫一扫

lintcode: Largest Rectangle in Histogram

DT_M 2022-12-01 阅读 160


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

用递增栈

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;
}
};


举报

相关推荐

0 条评论