您的位置:首页 > 其它

[LeetCode] Largest Rectangle in Histogram

2015-09-01 21:20 483 查看
This link has a very neat code, which is rewritten below using stack since the
push
and
pop
operations of it are
O(1)
time, while the
pop_back
and
push_back
of
vector
tend to be more time-consuming. This is also verified by the running time of the code on the OJ:
stack
version is generally 4ms to 8ms faster than
vector
version.

class Solution {
public:
int largestRectangleArea(vector<int>& height) {
height.push_back(0);
int n = height.size(), area = 0;
stack<int> indexes;
for (int i = 0; i < n; i++) {
while (!indexes.empty() && height[indexes.top()] > height[i]) {
int h = height[indexes.top()]; indexes.pop();
int l = indexes.empty() ? -1 : indexes.top();
area = max(area, h * (i - l - 1));
}
indexes.push(i);
}
return area;
}
};


Moreover, it would be better to keep
height
unmodified. So we loop for
n + 1
times and manually set the
h = 0
when
i == n
. The code is as follows.

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