您的位置:首页 > 其它

【Leetcode】Largest Rectangle in Histogram

2014-03-19 21:27 344 查看
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.

class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int max_area = 0;
stack<int> s;
height.push_back(0);
int i = 0;
while (i < height.size()) {
if (s.empty() || height[s.top()] < height[i]) {
s.push(i++);
} else {
int t = s.top();
s.pop();
max_area = max(max_area,
height[t] * (s.empty() ? i : i - s.top() - 1));
}
}
return max_area;
}
};


View Code
O(n2)的算法还是很好想的,但是如果借用数据结构--栈,可以使复杂度降低。

从左向右扫描数组,如果bar递增,则入栈,遇到第一个下降的bar时,开始出栈,计算从该bar(不含)到栈顶元素(含)之间形成的矩形面积,直到遇到栈里第一个低于它的bar,此时可以继续向前扫描下一个元素。

栈里维护的是递增序列。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: