[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
Moreover, it would be better to keep
pushand
popoperations of it are
O(1)time, while the
pop_backand
push_backof
vectortend to be more time-consuming. This is also verified by the running time of the code on the OJ:
stackversion is generally 4ms to 8ms faster than
vectorversion.
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
heightunmodified. So we loop for
n + 1times and manually set the
h = 0when
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; } };
相关文章推荐
- 【后缀数组】 POJ 3882 Stammering Aliens 可重叠出现k次字符串
- maven仓库查询地址
- Odoo(OpenERP)学习资源
- UDP通信过程
- POJ3264——Balanced Lineup 倍增RMQ裸题
- Uvalive 6428 A+B(扩展欧几里得算法)
- 轻松python之文件专题-搜索文本并写入文件专题
- 轻松python之文件专题-搜索文本并写入文件专题
- USACO 1.2 Palindromic Squares
- Android之Adapter用法总结
- QSetting Qt配置文件使用说明
- Windows内核编程基础篇之文件操作(一)
- 设计一种缓存机制,缓存最近几次查询的结果
- 基于zepto的手机焦点图touchstart touchmove
- ios 的 工程内的多Targets有什么用
- 聊天界面的制作(二)——发送消息后ListView左右布局显示
- HTML5的Web Storage
- C++ 浮点数的存储结构
- 查询语句
- Codeforces 57C Array dp暴力找到规律