您的位置:首页 > 其它

Largest Rectangle in Histogram

2017-05-21 19:12 169 查看

Largest Rectangle in Histogram

标签(空格分隔): leetcode, 算法,堆栈

1. 题目

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 heights = [2,1,5,6,2,3],

return 10.

2. 解答

解法一:暴力法

对柱状图的每一项,向前向后比较找出它能行程的面积最大的矩形。

class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if (heights.empty()) {
return 0;
}
int maxArea = heights[0];
for (int i = 0; i < heights.size(); ++i) {
int area = heights[i];  //柱状图中的每一项能形成的最大面积
for (int j = i + 1; j < heights.size(); ++j) {
if (heights[j] >= heights[i]) {
area += heights[i];
} else {
break;
}
}
for (int k = i - 1; k >= 0; --k) {
if (heights[k] >= heights[i]) {
area += heights[i];
} else {
break;
}
}
if (area > maxArea) {
maxArea = area;
}
}
return maxArea;
}
};


然而由于超时无法通过o(n^2)。

解法二:利用栈

利用栈构造非递减序列, 参考博客

class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int maxArea = 0;
stack<int> s;
for (vector<int>::size_type i = 0; i < heights.size(); ++i) {
if (s.empty() || s.top() <= heights[i]) {
s.push(heights[i]);
} else {
int popCnt = 0;
while (!s.empty() && s.top() > heights[i]) {
maxArea = max(maxArea, s.top() * (popCnt + 1));
s.pop();
++popCnt;
}
while(popCnt) {
s.push(heights[i]);
--popCnt;
}
s.push(heights[i]);
}
}
int popCnt = 0;
while (!s.empty()) {
maxArea = max(maxArea, s.top() * (popCnt + 1));
s.pop();
++popCnt;
}
return maxArea;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode