84. Largest Rectangle in Histogram
来源:互联网 发布:人有多复杂知乎 编辑:程序博客网 时间:2024/05/22 05:52
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 = 10
unit.
For example,
Given heights = [2,1,5,6,2,3]
,
return 10
.
假设处理完6之后,遇到了一个4,这是会先计算5*2 (因为5>4),然后再判断4和栈顶的1,此时4>1,那么就会插入栈顶,这时候下一个遇到比4小的话,那么就会计算4*3=12。所以其实这个栈维护的是一个矩形的底一样的长度。因为4会比5和6小(前几部有了判断),所以4*3是正确的。代码如下:时间复杂度为O(n),空间复杂度为O(n)
Code:(LeetCode运行12ms)
class Solution {public: int largestRectangleArea(vector<int>& heights) { stack<int> Stack; //最后入栈一次0,如上图中最后一直递增,最后不会处理,插入0后则会进行处理 heights.push_back(0); int result = 0; for (int i = 0; i < heights.size(); ) { if (Stack.empty() || heights[i] > heights[Stack.top()]) { Stack.push(i++); } else { int temp = Stack.top(); Stack.pop(); result = max(result, heights[temp] * (Stack.empty() ? i : i - Stack.top() - 1)); } } return result; }};
阅读全文
0 0
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. largest rectangle in histogram
- 84. Largest Rectangle in Histogram
- 84.Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 84. Largest Rectangle in Histogram
- 如何为微服务选择数据库
- 【爆炸总结】NOIp2017赛(Bao)后(Zha)总结
- 机器学习经典书籍
- ora-28014:cannot drop administrative users
- 什么是运维
- 84. Largest Rectangle in Histogram
- Spring与hibernate整合
- Android-自定义View实现二维码网格扫描+纵向雷达的扫描效果
- 配置Tensorflow-GPU版本
- Mysql查询语句
- 使用jquery.lazyload进行图片懒加载
- windows下 安装 rabbitMQ 及操作常用命令
- CentOS与Ubuntu有什么不同?
- 2017.11.14 linux学习