[LeetCode] Largest Rectangle in Histogram

本文介绍了一种利用栈优化计算直方图中最大矩形面积的方法,相较于使用向量,此方法通常能提高4到8毫秒的运行速度。

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.

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int>& height) {
 4         height.push_back(0);
 5         int n = height.size(), area = 0;
 6         stack<int> indexes;
 7         for (int i = 0; i < n; i++) {
 8             while (!indexes.empty() && height[indexes.top()] > height[i]) {
 9                 int h = height[indexes.top()]; indexes.pop();
10                 int l = indexes.empty() ? -1 : indexes.top();
11                 area = max(area, h * (i - l - 1));
12             }
13             indexes.push(i);
14         }
15         return area; 
16     }
17 };

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.

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int>& height) {
 4         int n = height.size(), area = 0, h, l;
 5         stack<int> indexes;
 6         for (int i = 0; i <= n; i++) {
 7             while (i == n || (!indexes.empty() && height[indexes.top()] > height[i])) {
 8                 if (i == n && indexes.empty()) h = 0, i++;
 9                 else h = height[indexes.top()], indexes.pop();          
10                 l = indexes.empty() ? -1 : indexes.top();
11                 area = max(area, h * (i - l - 1));
12             }
13             indexes.push(i);
14         }
15         return area;
16     }
17 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4776921.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值