题目
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.
思路
我们通过一个栈记录上升的柱子,如果如果下降的柱子,可以开始计算栈顶和之前柱子构建的矩形的面积。栈保存的是柱子的下标,而不是柱子的高度,目的是方便计算矩形的面积。遇到上升的柱子,就把柱子对应的下标压入栈。
代码
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int>& height) {
int maxArea = 0;
int size = height.size();
if(size <= 0){
return maxArea;
}
stack<int> indexStack;
int top,width;
for(int i = 0;i < size;++i){
if(indexStack.empty() || height[indexStack.top()] <= height[i]){
indexStack.push(i);
}
else{
top = indexStack.top();
indexStack.pop();
width = indexStack.empty() ? i : (i - indexStack.top() - 1);
maxArea = max(maxArea,height[top] * width);
--i;
}
}
while(!indexStack.empty()){
top = indexStack.top();
indexStack.pop();
width = indexStack.empty() ? size : (size - indexStack.top() - 1);
maxArea = max(maxArea,height[top] * width);
}
return maxArea;
}
};
int main(){
Solution s;
vector<int> height = {4,2,0,3,2,5};
cout<<s.largestRectangleArea(height)<<endl;
return 0;
}
运行时间
<script type="text/javascript">
$(function () {
$('pre.prettyprint code').each(function () {
var lines = $(this).text().split('\n').length;
var $numbering = $('<ul/>').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i <= lines; i++) {
$numbering.append($('<li/>').text(i));
};
$numbering.fadeIn(1700);
});
});
</script>
分享到:
相关推荐
LeetCode题目Largest Rectangle in Histogram 解答
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
JVM 基础 JAVA 并发 JVM 性能调优 LeetCode 算法 .......
LeetCode.370.区间加法器解法:差分数组assert nums.length > 0;// 构造差分数组public void increment(i
Leetcode Chrome extension..zip,Leetcode Chrome扩展。
My Solutions to Leetcode Database problems. 我的 Leetcode 数据.zip
leetcode-editor,在ide中做leetcode练习,支持leetcode.com和leetcode-cn.com,以满足练习的基本需求。理论上支持:intellij idea phpstorm webstorm pycharm rubymine appcode clion goland datagrip rider mps ...
用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现Leetcode题目.zip用C语言实现...
LeetCode.swift.zip,很久以前,有一堆算法,他对斯威夫特略知一二。
LeetCode刷题题解.rar
leetcode - shuzu.html
LeetCode刷题手册.docx
LeetCode_book.rar
LeetCode-源码.rar
Leetcode-源码.rar
LeetCode-master.rar
leetcode-study.zip
玩转LeetCode算法题.pdf
谷歌高畅、BAT霜神leetcode刷题笔记.zip