leetcode 084 —— Largest Rectangle in Histogram
来源:互联网 发布:淘宝店铺封了怎么激活 编辑:程序博客网 时间:2024/06/05 01:15
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 height = [2,1,5,6,2,3]
,
return 10
.
思路:此题最容易想到的是中间往两边扫描,但是这种方法时间是 O(n2),看到提示是栈,那么就用栈存储递增序列,如果出现降序,则计算最大值,然后将适量的栈顶元素入栈,继续往后扫描。虽然时间是O(n),但是在网上找到了新的方法,只将栈顶元素的下标入栈。不得不服。链接在这里
我的拙劣代码
class Solution {public:int largestRectangleArea(vector<int>& height) {int n = height.size();int i = 0;int maxS = 0;stack<int> stk;while (i < n){stk.push(height[i]);while (i + 1 < n&&height[i + 1] >= height[i]){ // 存放递增序列stk.push(height[++i]);}if (i + 1 == n){ //末端为递增序列int len = 1;while (!stk.empty()){maxS = max(maxS, stk.top()*len);stk.pop();len++;}break;}else{ //i+1为小于栈顶的数int len = 1;while (!stk.empty()&&height[i + 1] < stk.top()){maxS = max(maxS, stk.top()*(len));stk.pop();len++;}while (len - 1){stk.push(height[i + 1]);len--;}i++;}}return maxS;}};
网上的代码
class Solution {public:int Max(int a, int b){ return a > b ? a : b; }int largestRectangleArea(vector<int> &height) {height.push_back(0);stack<int> stk;int i = 0;int maxArea = 0;while (i < height.size()){if (stk.empty() || height[stk.top()] <= height[i]){ //递增序列则入栈stk.push(i++);}else {int t = stk.top();stk.pop();maxArea = Max(maxArea, height[t] * (stk.empty() ? i : i - stk.top() - 1));}}return maxArea;}};
0 0
- LeetCode —— Largest Rectangle in Histogram
- leetcode——Largest Rectangle in Histogram
- leetcode 084 —— Largest Rectangle in Histogram
- leetcode-084:Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram [084]
- 084 Largest Rectangle in Histogram [Leetcode]
- [leetcode] Largest Rectangle in Histogram——惊天动地的代码@
- 【leetcode】Array——Largest Rectangle in Histogram(84)
- LeetCode: Largest Rectangle in Histogram
- LeetCode Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- [leetcode] Largest Rectangle in Histogram
- [LeetCode]Largest Rectangle in Histogram
- Leetcode: Largest Rectangle in Histogram
- [leetcode]Largest Rectangle in Histogram
- CALayer
- linux mount命令详解
- android学习之屏幕解锁
- 创建临时表,作用:插入数据,取数据,取完数据自动删除。
- 动态规划_记忆化搜索
- leetcode 084 —— Largest Rectangle in Histogram
- win8(64位)下memcache安装时报错“ failed to install service or service already installed”
- Editplus notepad++ Gedit UltraEdi对比
- 如何用Git GUI下载Spring Framework源码
- 南邮 OJ 1070 南邮仙林自行车停放场
- Java基础--重温Java的继承和重写
- android 闪屏
- oracle database 11g 架构图
- CSU 1469 Change The Handles acm 模拟题