leetcode笔记:Largest Rectangle in Histogram
来源:互联网 发布:吉永小百合知乎 编辑:程序博客网 时间:2024/06/06 01:29
Largest Rectangle in Histogram
Total Accepted: 8795 Total Submissions: 42970My SubmissionsGiven 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
.
这道题想了良久,感觉没什么思路,看了leetcode大神们的代码,令人叹服……
还是做做笔记吧。
主要思路:我们知道,每个木板将对应多个包含自身的直方图面积,我们从中选取最大的一个面积。
以上题为例,height[1]对应的包含自身直方图面积集合为{1, 2, 3, 4, 5, 6 } ,我们只需要知道最大的面积 6 即可,其它的面积就不用考虑。
我们就比较所有height[i] 对应最大直方图面积,把整体最大的直方图面积记为maxArea。
分析到这,我们很明显的可以知道时间复杂度为O(n)。
现在关键问题就变为如何得到height[i]对应的最大直方图面积。
这里用一个栈s来保存之前的元素索引。
s为空时,直接让 i 栈;
当height[i]<height[s.top()]时,说明height[s.top()]对应的直方图面积不会再增加了,此时达到最大,可以出栈了;
当height[i]>=height[s.top()]时,说明height[s.top()]对应的直方图面积还是有潜力增加的哈,此时,i 入栈,++i 。
以上取 i 从 0 到 n-1 。
当 i 达到n 时,而 栈不为空,说明还有部分height中元素对应的最大直方图面积没有求出来……
于是,当栈不为空时,求 height[s.top()]对应最大直方图面积。
我整理思路后,重新写了一份代码,下面贴出代码吧
int largestRectangleArea(vector<int> &height) { if(height.empty()){ return 0; } stack<int> s; int i=0, n=height.size(),maxArea=0,top=0; while(i<n){ if(s.empty()||height[s.top()]<=height[i]){ s.push(i); ++i; }else{ top=s.top(); s.pop(); maxArea=max(maxArea,height[top]*(s.empty()?i:i-s.top()-1)); } } while(!s.empty()){ top=s.top(); s.pop(); maxArea=max(maxArea,height[top]*(s.empty()?n:n-s.top()-1)); } return maxArea; }
- 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
- 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
- 张艺谋主动提及超生:瞒着八旬老母却被播进新闻
- google page rank 解释
- R语言与函数估计学习笔记(核方法与局部多项式)
- Cocos2d-x CocosBuilder使用教程(一)HelloCocosBuilder
- 数组和指针的注记
- leetcode笔记:Largest Rectangle in Histogram
- TI C66x DSP 四种内存保护问题 -之- CPU访问corePac内部资源时的内存保护问题
- 五月优惠强势来袭,信盈达嵌入式学习,到底多优惠?由你来说!
- 隐藏TabBar的一些方法小结
- 长颈鹿类对动物类的继承
- Web开发基本准则-55实录-Web访问安全
- R语言与函数估计学习笔记(样条方法)
- deep learning reading list
- 算法——基础篇——字母图形