[LeetCode]Largest Rectangle in Histogram
2015-11-22 16:17
471 查看
题目解析:(链接)
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 =
The largest rectangle is shown in the shaded area, which has area =
For example,
Given height =
return
Subscribe to see which companies asked this question
解题思路:
O(n^2)的代码很好写,下面是copy来的O(n)的解题思路:
原帖地址:http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
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 =
10unit.
For example,
Given height =
[2,1,5,6,2,3],
return
10.
Subscribe to see which companies asked this question
解题思路:
O(n^2)的代码很好写,下面是copy来的O(n)的解题思路:
原帖地址:http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
class Solution { public: int largestRectangleArea(vector<int>& height) { stack<int> cache; int result = 0; height.push_back(0); for (int i = 0; i < height.size(); ) { if (cache.empty() || height[i] >= height[cache.top()]) { cache.push(i++); } else { int index = cache.top(); cache.pop(); int muliply = cache.empty()? i : i - cache.top() - 1; result = max(result, height[index] * muliply); } } return result; } };
相关文章推荐
- C# 构造函数与析构函数
- SqlConnectionStringBuilder基础
- CMWAP 和 CMNET 的区别是什么?
- Java I/O底层是如何工作的?
- CityEngine CGA语法之替换函数 i(insert)
- 回调函数--讲解的比较深入浅出的。
- php json数据使用gzip压缩输出
- AJAX请求WebService
- C语言数据类型的转换
- birt 报表环境搭建
- zzulioj 1787: 生化危机 (vector+dfs) 好题
- MySQL日期数据类型、MySQL时间类型使用总结
- C语言 malloc calloc realloc 区别
- 骨牌铺方格
- 生成系列命令的modbus命令(crc校验)
- ViewPager 判断左右滑动的方向
- 第十一周实践项目~验证算法 层次遍历算法的验证
- DFS求解素数环问题
- windows下安装Appserv等php套件之后无法进入数据库管理的问题
- POJ1073(2集合并查集)